[英]Python: iterate through a list
I´ve a mind challenge riddle that i want to resolve using python. 我想要使用python解决一个心灵挑战之谜。 They give 4 numbers (25, 28, 38, 35) and they want us to place the numbers in ...+...-...=... One possible solution is 25+38-35=28.
他们给出4个数字(25,28,38,35),他们希望我们将数字放在...... + ... - ... = ......一个可能的解决方案是25 + 38-35 = 28。 I´ve tried to, making a list from the numbers, iterate them with some loops and an if: lst=[25, 28, 38, 35]
我试过,从数字中创建一个列表,用一些循环和if:lst = [25,28,38,35]迭代它们
for z in lst:
for x in lst:
for c in lst:
for v in lst:
if z+x-c==v:
print z,x,c,v
But when a run the for loops they repeat the numbers, (25+25-25=25) and that don´t work. 但是当运行for循环时,他们会重复这些数字,(25 + 25-25 = 25)并且不起作用。 How can i solve it?
我怎么解决呢?
As Luis' comment hinted, a good approach is 正如路易斯的评论所暗示的那样,一个好的方法是
import itertools
for z, x, c, v in itertools.permutations(lst):
if z+x-c==v:
print z,x,c,v
"flat is better than nested", as import this
at an interactive Python prompt will remind you:-) “flat比嵌套更好”,因为在交互式Python提示符下
import this
会提醒你:-)
Def recadd(lis):
If lis[0] + lis[1] - lis[2]] = lis[3]:
return lis
Else:
recadd(lis[3] + lis[0:2])
recadd(lis[0] + lis[3] + lis[1:2])
recadd(lis[0:1] + lis[3]. + lis[2])
Quick and dirty hack on my mobile, could be elegantly expanded for k numbers, untested but it should work. 在我的手机上快速而肮脏的黑客,可以优雅地扩展为k号码,未经测试,但它应该工作。
Edit: realized this won't work if there is no solution.infinite recursion... 编辑:意识到如果没有解决方案,这将无法工作。无限递归...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.