题解 | #24点游戏算法#

24点游戏算法

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

用循环,没有用递归。

def gen(a):
    b = len(a)
    for i in range(0, b):
        c = a[:]
        num1 = c.pop(i)
        for j in range(0, b - 1):
            d = c[:]
            num2 = d.pop(j)
            yield d + [num1 + num2]
            yield d + [num1 - num2]
            yield d + [num1 * num2]
            if not (abs(num2) < 1e-6):
                yield d + [num1 / num2]
'''
b = gen([1,2,3])
for i in b:
    print(i)
'''

o = input()
a = list(map(int, o.split()))

def check(a):
    gen_list = [gen(a)]

    while len(gen_list):
        try:
            res = next(gen_list[-1])
            if len(res) == 1:
                if abs(res[0] - 24) < 1e-6:
                    return 'true'
                    break
            else:
                gen_list.append(gen(res))
        except StopIteration:
            gen_list.pop(-1)
    
    return 'false'

print(check(a))

全部评论

相关推荐

05-12 11:09
已编辑
门头沟学院 后端
已注销:没必要放这么多专业技能的描述。这些应该是默认已会的,写这么多行感觉在凑内容。项目这块感觉再包装包装吧,换个名字,虽然大家的项目基本都是网上套壳的,但是你这也太明显了。放一个业务项目,再放一个技术项目。技术项目,例如中间件的一些扩展和尝试。
点赞 评论 收藏
分享
04-25 19:29
已编辑
宁波大学 运营
被普调的六边形战士很高大:你我美牛孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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