2014-03-30 126 views
-3

我想打印集合中所有可能的3个数字组合(0 ... n-1),而每个组合都是唯一的。我通过这段代码获取变量ñPython中一组3个数字的所有可能组合

n = raw_input("Please enter n: ") 

但我被困在未来与算法。请帮忙吗?

+0

你尝试过什么吗?在你的问题中添加你的代码会很好。 – abhishekgarg

回答

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

效率最低的方式 – kingmakerking

1

itertools是你的朋友在这里,特别是permutations

演示:

from itertools import permutations 

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

这是假设你有Python的2.6或更高版本。

+0

我认为你的意思是'itertools.combinations' – Duncan

+0

@Duncan我认为OP的组合定义可能比编程更普遍,所以我决定包含它。 –

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

这会为你使用Python比后来的工作,只要2.6

1

如果你想所有重复的可能组合值和位置不同,你需要使用的产品是这样的:

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

例如,如果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)]) 

希望这有助于

相关问题