Recursive function to develop permutations

Hung Jung Lu hungjunglu at yahoo.com
Fri Oct 22 10:11:42 EDT 2004


hungjunglu at yahoo.com (Hung Jung Lu) wrote:
> No if/else statements. No explicit recursion. And it works for
> zero-length lists as well. Now, if someone could do the general P(n,
> k) and C(n, k) versions, I'd appreciate it. :)

Well, here they are: (for functional people, basically I used
tail-call and parameter list to emulate looping variables... standard
trick, nothing new. The formulas might be further simplified?)

permutations = lambda Xs, k: [p[0] for p in reduce(lambda r, i:
[[x+[y[i]], y[:i]+y[i+1:]] for (x, y) in r for i in range(len(y))],
range(k), [[[], Xs]])]

combinations = lambda Xs, k: [p[0] for p in reduce(lambda r, i:
[[x+[y[i]], y[i+1:]] for (x, y) in r for i in range(len(y))],
range(k), [[[], Xs]])]

slot_machine_combinations = lambda Xs, k: [p[0] for p in reduce(lambda
r, i: [[x+[y[i]], y] for (x, y) in r for i in range(len(y))],
range(k), [[[], Xs]])]

sample = ['a', 'b', 'c', 'd']
print permutations(sample, 2)
print combinations(sample, 2)
print slot_machine_combinations(sample, 2)

The three formulas only differ in the treatment of the y[] lists in
looping. That part can be parametrized into separate lambdas if so
desired.

permutations: y --> y[:i] + y[i+1:]
combinations: y --> y[i+1:]
slot_machine_combinations: y --> y

Hung Jung



More information about the Python-list mailing list