题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
# 将4个数排列组合有4!=24种情况;4个数中间的3个计算符号每个都有加减乘除4种可能,共有4**3 =64种可能 # 所以最多循环4!*4**3 = 24*64 次遍历全部情况,其中任意情况得到24即可退出循环。 from itertools import permutations l_num = list(map(str,input().split(' '))) l_signal = ['+','-','*','/'] l_possible_con =list(permutations(l_num)) new_l = [] is_24 =0 for x1 in l_signal: for x2 in l_signal: for x3 in l_signal: for new_l in l_possible_con: new_l = list(new_l) y = '((' + new_l[0] + x1 + new_l[1] + ')' + x2 + new_l[2] + ')' + x3 + new_l[3] y1 =eval(y) if y1 == 24: is_24 = 1 break if is_24 == 1: print('true') else : print('false')