题解 | #24点游戏算法#

24点游戏算法

https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb

因为加减护卫逆运算,乘除互为逆运算,将24运用递归轮循加减乘除列表头一个数字,直到剩余一个元素,得到的结果和最后一个数字比较,如果相等则返回true,否则false.
def tfp(list:list, num):
    if len(list) == 1:
        return list[0] == num
    i = 4
    while i:
        list.append(list.pop(0))
        if tfp(list[1:], num+list[0]) or tfp(list[1:], num-list[0])\
        or tfp(list[1:], num*list[0]) or tfp(list[1:], num/list[0]):
            return True
        i -= 1    
    return False

l = list(map(int, input().split()))
print('true') if tfp(l, 24) else print('false')


全部评论

相关推荐

牛客36400893...:我不是这个专业的,但是简历确实没有吸引我的亮点,而且废话太多没耐心看
0offer是寒冬太冷还...
点赞 评论 收藏
分享
饿魔:看到在线简历了吧
点赞 评论 收藏
分享
评论
1
3
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务