def generate_oriented_forest(n):
 P = list(range((-1), n))
 while True:
  (yield P[1:])
  if (P[n] > 0):
   P[n] = P[P[n]]
  else:
   for p in range((n - 1), 0, (-1)):
    if (P[p] != 0):
     target = (P[p] - 1)
     for q in range((p - 1), 0, (-1)):
      if (P[q] == target):
       break
     offset = (p - q)
     for i in range(p, (n + 1)):
      P[i] = P[(i - offset)]
     break
   else:
    break

def generate_oriented_forest ( n ) : P = list ( range ( ( - 1 ) , n ) ) while True : ( yield P [ 1 : ] ) if ( P [ n ] > 0 ) : P [ n ] = P [ P [ n ] ] else : for p in range ( ( n - 1 ) , 0 , ( - 1 ) ) : if ( P [ p ] != 0 ) : target = ( P [ p ] - 1 ) for q in range ( ( p - 1 ) , 0 , ( - 1 ) ) : if ( P [ q ] == target ) : break offset = ( p - q ) for i in range ( p , ( n + 1 ) ) : P [ i ] = P [ ( i - offset ) ] break else : break
this algorithm generates oriented forests .