24点计算
想做一个24点的计算程序,不知道哪里有错,计算不出答案,麻烦各位大大帮忙看看如下:
import itertools as itrs
a=
f = []
ops = []
trylist = []
trylist_1 = []
# str = [,op,a,op,a,op,a]]
for num_seq in itrs.permutations(a):
f.append(list(num_seq))
#print (f)
for op in itrs.product(r'+-*/',repeat = 3):
ops.append(list(op))
#print (ops)
# for each in ops:
# for i in range (3):
# ops_list
for formula in itrs.product(ops,f):
trylist.append(formula)
for each in trylist:
each = each + each
trylist_1.append(each)
formula_1 = []
for each in trylist_1:
t = each
each = each
each = t
a = each
each = each
each = a
b = each
each = each
each = b
for each in trylist_1:
x = ''
for each_item in each:
x += str(each_item)
formula_1.append(x)
# print(formula_1)
for each in formula_1:
if eval(each) == 24:
print(each, ' = 24')
else:
print('no solution')
帮你优化了下代码,你的代码应该进入死循环了:
import itertools as itrs
a=
f = []
ops = []
result = []
for num_seq in itrs.permutations(a):
f.append(list(num_seq))
for op in itrs.product(r'+-*/',repeat = 3):
ops.append(list(op))
flag = 0
for formula in itrs.product(ops,f):
temp = )]
for each in range(len(formula)):
temp.append(formula)
temp.append(str(formula))
result.append(' '.join(temp))
for i in set(result):
if eval(i) == 24:
print(i, '= 24')
flag = 1
if flag == 0:
print('no solution')
输出结果:
4 * 6 * 1 * 1 = 24
1 * 4 / 1 * 6 = 24
6 * 4 * 1 * 1 = 24
6 * 1 * 1 * 4 = 24
4 * 1 / 1 * 6 = 24
1 * 6 * 1 * 4 = 24
6 * 4 / 1 / 1 = 24
4 * 6 / 1 * 1 = 24
6 * 1 * 4 / 1 = 24
6 / 1 * 4 * 1 = 24
4 / 1 * 1 * 6 = 24
6 * 1 / 1 * 4 = 24
4 * 1 * 6 * 1 = 24
4 * 6 - 1 + 1 = 24
4 / 1 / 1 * 6 = 24
6 * 1 * 4 * 1 = 24
4 * 6 * 1 / 1 = 24
4 * 1 * 1 * 6 = 24
4 * 6 / 1 / 1 = 24
6 * 4 + 1 - 1 = 24
6 * 4 - 1 + 1 = 24
1 * 1 * 6 * 4 = 24
1 * 1 * 4 * 6 = 24
6 / 1 / 1 * 4 = 24
6 * 4 * 1 / 1 = 24
4 * 6 + 1 - 1 = 24
1 * 6 / 1 * 4 = 24
1 + 4 * 6 - 1 = 24
1 - 1 + 4 * 6 = 24
4 * 1 * 6 / 1 = 24
1 / 1 * 4 * 6 = 24
1 * 4 * 6 * 1 = 24
1 * 4 * 6 / 1 = 24
1 / 1 * 6 * 4 = 24
6 / 1 * 1 * 4 = 24
1 * 6 * 4 * 1 = 24
1 + 6 * 4 - 1 = 24
1 * 6 * 4 / 1 = 24
1 * 4 * 1 * 6 = 24
4 / 1 * 6 * 1 = 24
1 - 1 + 6 * 4 = 24
6 / 1 * 4 / 1 = 24
4 / 1 * 6 / 1 = 24
6 * 4 / 1 * 1 = 24
Twilight6 发表于 2020-11-20 15:53
帮你优化了下代码,你的代码应该进入死循环了:
谢谢您的优化,只是我没找到自己的进入死循环的地方,测试了几次,感觉可能在倒数第二个循环里似的,就是字符串化的那个循环。您能帮忙指导一下么?
另外很感谢您提供的方案,把两个元组合并得很巧。 gonorth 发表于 2020-11-20 19:06
谢谢您的优化,只是我没找到自己的进入死循环的地方,测试了几次,感觉可能在倒数第二个循环里似的,就是 ...
刚刚看了下你代码,并不是死循环,你代码都是用的是 for 循环,也没有对列表进行重复添加
是因为排列后的数据太过庞大,导致结果出现的比较慢
Twilight6 发表于 2020-11-20 19:14
刚刚看了下你代码,并不是死循环,你代码都是用的是 for 循环,也没有对列表进行重复添加
是因为 ...
嗯,确实,没有重复覆盖。因为我是每个环节都查一下,看看对不对。谢谢您的帮助。我知道为啥感觉不对了,
最后一个for,我应该改成
for each in list(set(formula_1)):
if eval(each) == 24:
print(each, ' = 24')
但是依然发现了一个问题,就是永远不能先算加减再算乘除。。。。
页:
[1]