使用 Python 的算术运算符和指定的数字 2、3、4、5构造一个表达式,使用所有的4个数字和3个运算符各一次,计算得到28,
1 2 3 4 5 6 7 8 9 10 11
| import random
num = list(input().split(" ")) notation = ['-', '+', '/', '*', '**','%'] answer = '' while answer != 28: sign = random.sample (notation, 3) figure = random.sample(num, 4) assembly = figure[0] + sign[0] + figure[1] + sign[1] + figure[2] + sign[2] + figure[3] answer = eval (assembly) print(assembly, "=", eval (assembly))
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import itertools
def twentyfour(cards): '''史上最短计算24点代码''' for nums in itertools.permutations(cards): for ops in itertools.product('+-*/', repeat = 3): bds1 = '({0}{4}{1}){5}({2}{6}{3})'.format(*nums, *ops) bds2 = '(({0}{4}{1}){5}{2}){6}{3}'.format(*nums, *ops) bds3 = '{0}{4}({1}{5}({2}{6}{3}))'.format(*nums, *ops) for bds in [bds1, bds2, bds3]: try: if abs(eval(bds) - 24.0) < 1e-10: return bds except ZeroDivisionError: continue return 'Not found!'
cards =[[1,1,1,8], [1,1,2,6]] for card in cards: print(twentyfour(card))
|