imre
imre

Reputation: 489

All possible combination of 3 numbers in a set in Python

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?

Upvotes: 0

Views: 13906

Answers (4)

anon582847382
anon582847382

Reputation: 20391

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.

Upvotes: 2

Ammar
Ammar

Reputation: 1314

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

Upvotes: 3

Dave Coffman
Dave Coffman

Reputation: 231

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

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

Upvotes: 10

alanmanderson
alanmanderson

Reputation: 8230

combos = []
for x in xrange(n):
    for y in xrange(n):
        for z in xrange(n):
             combos.append([x,y,z])

Upvotes: 1

Related Questions