简体   繁体   English

Python中一组3个数字的所有可能组合

[英]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.我想打印集合中 3 个数字的所有可能组合( 0 ... n-1 ),而这些组合中的每一个都是唯一的。 I get the variable n via this code:我通过以下代码获得变量n

n = raw_input("Please enter n: ")

But I'm stuck at coming up with the algorithm.但我坚持想出算法。 Any help please?请问有什么帮助吗?

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

This would work as long as you are using later than Python 2.6只要您使用的版本晚于 Python 2.6,这就会起作用

itertools is your friend here, specifically permutations . itertools是你的朋友,特别是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.这是假设您拥有 Python 2.6 或更新版本。

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:例如,如果 n = 3,输出将是:

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希望这可以帮助

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM