【问题标题】:Python implementation of the 24 game24款游戏的python实现
【发布时间】:2018-05-31 06:08:39
【问题描述】:

下面是我在 Python 2 中实现 24 游戏的尝试,我尝试遵循 leetcode 中指定的要求:https://leetcode.com/problems/24-game/description/

我的方法基本上是检查 4 个提供的数字的所有排列与 4 个操作中的 3 个操作(加、减、乘和除)的所有排列。

我使用iteratools.product() 来获取操作的排列,因为可能存在重复操作。

我有两个问题:

  1. 我不确定我的内部 for 循环中的 3 块代码是否涵盖所有情况,如果是,我如何证明这一点?例如,我不确定是否应该检查((W op (X op Y) op Z))
  2. 我认为在最坏的情况下会有 24 * 64 * 9 = 13824 次计算。可以减少计算次数吗?

import itertools
class Solution(object):
    def judgePoint24(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        Ops = list(itertools.product([add,sub,mul,div], repeat=3))
        for ns in set(itertools.permutations(nums)):
            for ops in Ops:
                # W = ns[0], X = ns[1], Y = ns[2], Z = ns[3]

                # (((W op X) op Y) op Z)
                result = ops[0](ns[0], ns[1])
                result = ops[1](result, ns[2])
                result = ops[2](result, ns[3])
                if 23.99 < result < 24.01:
                    return True

                # (Z op (Y op (W op X)))
                result = ops[0](ns[0], ns[1])
                result = ops[1](ns[2], result)
                result = ops[2](ns[3], result)
                if 23.99 < result < 24.01:
                    return True

                # ((W op X) op (Y op Z))
                result1 = ops[0](ns[0], ns[1])
                result2 = ops[1](ns[2], ns[3])
                result = ops[2](result1, result2)
                if 23.99 < result < 24.01:
                    return True
        return False

def add (a, b):
    return a+b
def sub (a, b):
    return a-b
def mul (a, b):
    return a*b
def div (a, b):
    if b == 0:
        return 0
    return a/float(b)

【问题讨论】:

    标签: python algorithm python-2.7 performance refactoring


    【解决方案1】:

    这里有一些通用的指针。

    1. 您可以cache 一些计算的结果。在您的情况下,这可能不是必需的,但您应该知道如何权衡内存与时间。
    2. 您可以避免重复计算(表达式ops[0](ns[0], ns[1]) 在每次迭代中计算3 次)。获取一次结果并将其插入到其他表达式中。
    3. 最后一点引出了一个更普遍的考虑:每个表达式都可以表示为tree。现在,您正在以(几乎)随机顺序暴力破解所有可能的树。有没有办法以“更聪明”的顺序做到这一点?当然!如果前两个数字是99,而您在9*9+(x op y),那么您选择哪个操作以及其余两个数字是什么都没有关系 - 您将无法降到 24 . 当您不需要继续评估时,请尝试考虑更多“停止条件”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多