题解 | #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')


全部评论

相关推荐

认真搞学习:这么良心的老板真少见
点赞 评论 收藏
分享
07-18 14:34
门头沟学院 Java
感觉招聘要求好高,这都是招什么人才
电气电子小朋友:你都说了这是大疆,无人机顶级企业,薪资30k-50k,要求高是正常的
点赞 评论 收藏
分享
评论
1
3
分享

创作者周榜

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