|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
想做一个24点的计算程序,不知道哪里有错,计算不出答案,麻烦各位大大帮忙看看
如下:
import itertools as itrs
a= [5,5,2,4]
f = []
ops = []
trylist = []
trylist_1 = []
# str = [[a[i],op,a[i],op,a[i],op,a[i]]]
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[0] + each [1]
trylist_1.append(each)
formula_1 = []
for each in trylist_1:
t = each[0]
each[0] = each[3]
each[3] = t
a = each[2]
each[2] = each[4]
each[4] = a
b = each[4]
each[4] = each[5]
each[5] = 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= [1,6,4,1]
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 = [str(formula[1][0])]
for each in range(len(formula[0])):
temp.append(formula[0][each])
temp.append(str(formula[1][each+1]))
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
|
|