算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')
全部评论

相关推荐

求个付费实习岗位:这种就是吃满时代红利又没啥技术水平,只能靠压力学生彰显优越感的老登,别太在意了
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

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