Generator for k-permutations without repetition
Nis Jørgensen
nis at superlativ.dk
Wed Jul 4 09:09:50 EDT 2007
bullockbefriending bard skrev:
> On Jul 4, 7:09 pm, Nis Jørgensen <n... at superlativ.dk> wrote:
>> bullockbefriending bard skrev:
>> A quick solution, not extensively tested
>>
>> # base needs to be an of the python builtin set
>>
>> def k_perm(base,k):
>> for e in base:
>> if k == 1:
>> yield [e]
>> else:
>> for perm in k_perm(base-set([e]),k-1):
>> yield [e] + perm
>
> thank you!. i'll give this a try. seems to do exactly what i need.
> sorry about the ambiguity in my example. i chose 3 from 3 merely to
> keep the size of the example case small, without thinking enough about
> how it might cause confusion.
I managed to simplify it a little:
def k_perm(base,k):
if k == 0:
yield []
else:
for e in base:
for perm in k_perm(base-set([e]),k-1):
yield [e] + perm
Nis
More information about the Python-list
mailing list