首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python缩减条件表达式

Python缩减条件表达式
EN

Stack Overflow用户
提问于 2015-03-08 22:33:27
回答 2查看 897关注 0票数 1

我有9个变量a,b,c,d,e,f,g,h,i和i,在9内循环,从0到9,但范围可能不同。

我要他们的所有序列all防御,这样就没有重复的数字。

现在我有一个,下面:

代码语言:javascript
复制
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循环的范围不同呢?

提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-08 22:37:19

您只需使用itertools模块就可以做到这一点:

代码语言:javascript
复制
from itertools import permutations

for arrangement in permutations('abcdefghi', 9):
    print ''.join(arrangement)
票数 2
EN

Stack Overflow用户

发布于 2015-03-08 22:41:22

代码语言:javascript
复制
from itertools import permutations

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

这给

代码语言:javascript
复制
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

如果我想要的序列是a,b,c,e,g从0到9,d,f,h,i在1到5之间。

这有点复杂,但仍然可以实现。首先选择d..i中的值比较容易:

代码语言:javascript
复制
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)

这给

代码语言:javascript
复制
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-约束这样的约束解决程序(关于介绍,请参见python约束主页)。

然后你的解决方案看起来就像

代码语言:javascript
复制
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))

这给

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28932722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档