'''
Try online python:
  https://www.programiz.com/python-programming/online-compiler/
  https://replit.com/languages/python3
'''

# ----------------------------------------------------------------------------
#                              PERMUTATIONS
# Task:
# Generate all permutations of a given set of items.
# Technical note: A set is represented as a list.
# ----------------------------------------------------------------------------

def allperm1( mylist ):

  if len(mylist) == 1:
    return [mylist]

  shorterPerms = allperm1( mylist[1:] )

  result = []
  item1 = mylist[0]

  # insert item1 at all possible possitions
  # into each shorter permutation
  for perm in shorterPerms:
    result.append( [item1] + perm )
    for k in range( len(perm) ):
      result.append( perm[ :k+1] + [item1] + perm[k+1:] )

  return result




def allperm2 ( myList ):

  if len(myList) == 1:
    return [myList]

  # Run recursion on myList with one item removed
  # for each item in myList.
  # Prepend the removed item to each permutation returned
  # from the recursion.

  result = []
  for k in range( len(myList) ):
    item = myList[k]
    shorterList =  myList[ :k] + myList[k+1: ]
    shorterPerms = allperm2( shorterList )
    for perm in shorterPerms:
      result.append( [item] + perm )

  return result



def allpermx( myList ):
# Exercise:
# Generate only alternating permutations, these permutations
# do not contain three successive items in
# either increasing or decreasing order.
# In other words, the items in permutation go up and down, up and down... etc.

  if len(myList) == 1:  return [myList]

  # Run recursion on myList with one item removed
  # for each item in myList.
  # Prepend the removed item to each permutation returned
  # from the recursion.

  result = []
  for k in range( len(myList) ):
    item = myList[k]
    shorterList =  myList[ :k] + myList[k+1: ]
    shorterPerms = allpermx( shorterList )
    for perm in shorterPerms:
      # skip unwanted permutations:
      if (len(perm) >= 2) and ( (item < perm[0] and perm[0] <  perm[1]) or (item > perm[0] and perm[0] > perm[1] ) ):
         continue
      # otherwise register new permutation
      result.append( [item] + perm )

  return result

# ----------------------------------------------------------------------------
#   M A I N    -   e x p e r i m e n t s
# ----------------------------------------------------------------------------

seq = [1,2,3, 4,5,6,7]

perms = allpermx ( seq )
counter = 0
for p in perms:
  counter += 1
  print( counter, p )



