算24点 python

24点游戏算法

http://www.nowcoder.com/questionTerminal/fbc417f314f745b1978fc751a54ac8cb

提供一个思路吧
排列 + 逆波兰表达式

        # 建立一个逆波兰表达式,
        # A B OP C OP D OP 为合法的逆波兰表达式
        # A B OP C D OP OP 也是合法的
        """

        def calc(ex):
            nums = []
            for i in ex:
                if i in '+-*/':
                    if len(nums) < 2: return False
                    b = nums.pop()
                    a = nums.pop()
                    if i == '/' and eval(b) == 0: return False
                    nums.append(str(eval(a + i + b)))
                else:
                    nums.append(i)

            # if eval(nums[0]) == 24: print(ex) # print the correct expression
            return eval(nums[0]) == 24

        import itertools
        import sys
        for line in sys.stdin:
            inp = line.split()
            isfind = False
            for nums in itertools.permutations(inp):
                nums = list(nums)
                for op1, op2, op3 in itertools.product('+-*/', '+-*/', '+-*/'):
                    if (calc(nums[:2] + [op1] + nums[2:3] + [op2] + nums[3:4] + [op3]) or
                            calc(nums[:2] + [op1] + nums[2:4] + [op2, op3]) or
                            calc(nums[:3] + [op1, op2] + nums[3:4] + [op3]) or
                            calc(nums[:3] + [op1] + nums[3:4] + [op2, op3]) or
                            calc(nums[:4] + [op1, op2, op3])):
                        print('true')
                        isfind = True
                        break
                if isfind:
                    break
            if not isfind: print('false')
全部评论

相关推荐

12-18 19:36
已编辑
门头沟学院 Java
程序员牛肉:可以的,简历没毛病了。 虽然还是偏向同质化,不过学历不错。后续我觉得重心放到刷实习+摆脱同质化问题上
实习简历求拷打
点赞 评论 收藏
分享
10-31 20:07
门头沟学院 Java
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

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