Algorithm: combinations of (k) taken from (n) values
Matthew Hirsch
meh9 at cornell.edu
Thu Apr 6 16:04:14 EDT 2000
Hi All,
Onto the next question...
Can anyone think of an algorithm to store as lists all possible
combinations of k numbers taken from n possible numbers. For example,
given 5 values, I want to choose 2. The number of possible combinations
is given by 5!/(3!2!)=10. They are:
[0,1], [1,2], [2,3], [3,4]
[0,2], [1,3], [2,4]
[0,3], [1,4]
[0,4]
I have something like:
n=5
for first_choice in range(n):
for second_choice in range(first_choice+1,n):
for third_choice in range(second_choice+1,n):
print first_choice, second_choice, third_choice
The problem is that I'll be dealing with large combinations of numbers
and it doesn't make sense to continue writing nested for loops. I'm
trying to figure out something that generates all combinations, just
based on values of k and n. Any ideas?
Thanks for your help,
Matt
More information about the Python-list
mailing list