def _set_partitions(n):
 p = ([0] * n)
 q = ([0] * n)
 nc = 1
 (yield (nc, q))
 while (nc != n):
  m = n
  while 1:
   m -= 1
   i = q[m]
   if (p[i] != 1):
    break
   q[m] = 0
  i += 1
  q[m] = i
  m += 1
  nc += (m - n)
  p[0] += (n - m)
  if (i == nc):
   p[nc] = 0
   nc += 1
  p[(i - 1)] -= 1
  p[i] += 1
  (yield (nc, q))

def _set_partitions ( n ) : p = ( [ 0 ] * n ) q = ( [ 0 ] * n ) nc = 1 ( yield ( nc , q ) ) while ( nc != n ) : m = n while 1 : m -= 1 i = q [ m ] if ( p [ i ] != 1 ) : break q [ m ] = 0 i += 1 q [ m ] = i m += 1 nc += ( m - n ) p [ 0 ] += ( n - m ) if ( i == nc ) : p [ nc ] = 0 nc += 1 p [ ( i - 1 ) ] -= 1 p [ i ] += 1 ( yield ( nc , q ) )
cycle through all partions of n elements .