0

I want to print all possible combination of 3 numbers from the set (0 ... n-1), while each one of those combinations is unique. I get the variable n via this code:

n = raw_input("Please enter n: ")

But I'm stuck at coming up with the algorithm. Any help please?

1
  • did you try anything?? it would be nice to add your code in your question. Mar 30, 2014 at 20:34

4 Answers 4

10
from itertools import combinations
list(combinations(range(n),3))

This would work as long as you are using later than Python 2.6

3

If you want all the possible combinations with repetition in values and differ in position you need to use product like this:

from itertools import product
t = range(n)
print set(product(set(t),repeat = 3))

for example, if n = 3, the output will be:

set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)])

hope this helps

2

itertools is your friend here, specifically permutations.

Demo:

from itertools import permutations 

for item in permutations(range(n), 3): 
    print item

This is assuming you have Python 2.6 or newer.

2
  • I think you meant itertools.combinations
    – Duncan
    Mar 30, 2014 at 20:40
  • @Duncan I think the OP's definition of combinations might be more general than that of programming, so I decided to include it. Mar 30, 2014 at 20:46
1
combos = []
for x in xrange(n):
    for y in xrange(n):
        for z in xrange(n):
             combos.append([x,y,z])
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.