python源码24点(python实现24点)
本文目录一览:
Python编24点游戏
# !/usr/bin/python
# coding:utf8
'''
原始方法编24点游戏
'''
import itertools
import random
numlist = [random.randint(1, 13) for i in range(4)] # 随机4个数
print numlist
nlist = []
[nlist.append(nl) for nl in list(itertools.permutations(numlist)) if nl not in nlist] # 4个数排列组合,并在有重复数字时对组合去重
# print nlist
option = ['+','-','*','/']
olist = list(itertools.product(option,repeat=3)) # 操作符重复组合3位
# print olist
retlist = [[str(nl[0])+'*1.0']+[ol[0]]+[str(nl[1])+'*1.0']+[ol[1]]+[str(nl[2])+'*1.0']+[ol[2]]+[str(nl[3])+'*1.0'] for nl in nlist for ol in olist] # 拼凑4个数和3个操作符
# print retlist
# 括号的位置
# (0,3)(0,5)
# (2,5)(2,7)
# (4,7)
# (0,3)和(4,7)
lastlist = []
for ret in retlist:
if ('*' not in ret and '/' not in ret) or ('*' in ret and '/' in ret):
lastlist.append(''.join(ret))
else:
lastlist.append(''.join(['(']+ret[:3]+[')']+ret[3:]))
lastlist.append(''.join(['(']+ret[:5]+[')']+ret[5:]))
lastlist.append(''.join(ret[:2]+['(']+ret[2:5]+[')']+ret[5:]))
lastlist.append(''.join(ret[:2]+['(']+ret[2:7]+[')']))
lastlist.append(''.join(ret[:4]+['(']+ret[4:7]+[')']))
lastlist.append(''.join(['(']+ret[:3]+[')']+ret[3:4]+['(']+ret[4:7]+[')']))
# print lastlist
i = 0
for ll in lastlist:
try:
if eval(ll) == 24: # 计算,每位数*1.0,是防止出现12/5=2的情况
print ll.replace('*1.0','')+'=24' # 去掉'*1.0'
else:
i += 1
except ZeroDivisionError, e:
# print '除于0错误: '+ll.replace('*1.0','') # 表达式中有除于0的
i += 1
continue
if i == len(lastlist):
print 'no output!'
怎样用python算24点?
这个参考一下:是csdn的
输入4个数字, 输出所有用加减乘除结果为24的表达式. 代码如下:
def isEqual(num1, num2):
return
abs(num1 - num2) 1e-5;
# End of isEqual().
python编程:任意输入4个正整数,编程24点
from __future__ import division
import itertools
n = raw_input('input 4 number sep by comma: 1,2,3,4 - ')
t = list(itertools.permutations(n.split(','),4))
x = list(itertools.product(* (['+', '-', '*', '/'],) * 3))
for r in t:
for i in x:
if eval(("(((%s%s%s)%s%s)%s%s)") % (r[0],i[0], r[1], i[1], r[2], i[2], r[3])) == 24 :
print ("(((%s%s%s)%s%s)%s%s)=24") % (r[0],i[0], r[1], i[1], r[2], i[2], r[3])
暴力法行么?