2015-03-08 34 views
1

我有9個變量a,b,c,d,e,f,g,h,i和I將它們循環到9內循環從0到9.但範圍可能會有所不同。Python減少條件表達式

我想要它們的所有序列abcdefghi,這樣就沒有重複的數字。

現在我都這樣了,下面:

for a in range(0, 9): 
    for b in range(0,9): #it doesn't have to start from 0 
    .... 
     for i in range(0, 9): 
      if a != b and a != c ... a != i 
       b != c and b != d ... b != i 
       c != d and c != e ... c != i 
       ... h != i: 

       print (a,b,c,d,e,f,g,h,i) 

有9! =其中362880,

但是我怎樣才能減少條件表達式?而如果for循環的範圍不同呢?

在此先感謝!

+0

看看itertools模塊裏,我認爲['combinations'(HTTPS://docs.python .org/2/library/itertools.html#itertools.combinations)函數是你正在尋找的 – mkrieger1 2015-03-08 22:37:03

+0

這是一個排列組合。 – 2015-03-08 22:37:50

+0

你想要測試什麼?用文字說。幾乎可以肯定的是,這樣做很容易。 – will 2015-03-08 22:38:14

回答

2

你可以簡單地用itertools模塊做到這一點:

from itertools import permutations 

for arrangement in permutations('abcdefghi', 9): 
    print ''.join(arrangement) 
+0

我實際上是在尋找一種方法來減少條件表達式,但我認爲這種方法也可以。謝謝 – 2015-03-08 22:57:16

+0

你想讓我添加一個for循環版本嗎? – 2015-03-08 22:57:37

+0

不,但如果變量的域不是全部爲0到9,那麼該怎麼辦? – 2015-03-08 22:59:17

2
from itertools import permutations 

for perm in permutations(range(1, 10), 9): 
    print(" ".join(str(i) for i in perm)) 

這給

1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 9 8 
1 2 3 4 5 6 8 7 9 
1 2 3 4 5 6 8 9 7 
1 2 3 4 5 6 9 7 8 
1 2 3 4 5 6 9 8 7 

# ... etc - 9! = 362880 permutations 

,如果我想ABCDEFGHI這樣taht一個序列什麼,B ,c,e,g是從0到9的值,並且d,f,h,i在1到5的範圍內

這有點複雜,但仍然可以實現。這是比較容易挑值d..i第一:

from itertools import permutations 

for d,f,h,i,unused in permutations([1,2,3,4,5], 5): 
    for a,b,c,e,g in permutations([unused,6,7,8,9], 5): 
     print(a,b,c,d,e,f,g,h,i) 

這給

5 6 7 1 8 2 9 3 4 
5 6 7 1 9 2 8 3 4 
5 6 8 1 7 2 9 3 4 
5 6 8 1 9 2 7 3 4 
5 6 9 1 7 2 8 3 4 
5 6 9 1 8 2 7 3 4 
5 7 6 1 8 2 9 3 4 
5 7 6 1 9 2 8 3 4 
5 7 8 1 6 2 9 3 4 
5 7 8 1 9 2 6 3 4 

# ... etc - 5! * 5! = 14400 permutations 

對於你需要一個更通用的解決方案一般情況下(即數獨) - 約束求解像python-constraint (有關介紹,請參閱the python-constraint home page)。

那麼您的解決方案開始看起來像

from constraint import Problem, AllDifferentConstraint 

p = Problem() 
p.addVariables("abceg", list(range(1,10))) 
p.addVariables("dfhi", list(range(1, 6))) 
p.addConstraint(AllDifferentConstraint()) 

for sol in p.getSolutionIter(): 
    print("{a} {b} {c} {d} {e} {f} {g} {h} {i}".format(**sol)) 

這給

9 8 7 4 6 3 5 2 1 
9 8 7 4 5 3 6 2 1 
9 8 6 4 7 3 5 2 1 
9 8 6 4 5 3 7 2 1 
9 8 5 4 6 3 7 2 1 
9 8 5 4 7 3 6 2 1 
9 7 8 4 5 3 6 2 1 
9 7 8 4 6 3 5 2 1 
9 7 6 4 8 3 5 2 1 
9 7 6 4 5 3 8 2 1 
9 7 5 4 6 3 8 2 1 

# ... etc - 14400 solutions 
+0

除了它是字母a到i的排列。我通常試圖避免變量組合,因爲它與整個排列的事物相矛盾。 – 2015-03-08 22:54:32

+0

@MalikBrahimi:「我希望他們的所有序列都是abcdefghi,這樣就不會有重複的**號碼**」 - 我認爲他是想要數字。 – 2015-03-08 22:58:25