【发布时间】:2018-05-31 06:08:39
【问题描述】:
下面是我在 Python 2 中实现 24 游戏的尝试,我尝试遵循 leetcode 中指定的要求:https://leetcode.com/problems/24-game/description/
我的方法基本上是检查 4 个提供的数字的所有排列与 4 个操作中的 3 个操作(加、减、乘和除)的所有排列。
我使用iteratools.product() 来获取操作的排列,因为可能存在重复操作。
我有两个问题:
- 我不确定我的内部 for 循环中的 3 块代码是否涵盖所有情况,如果是,我如何证明这一点?例如,我不确定是否应该检查
((W op (X op Y) op Z))。 - 我认为在最坏的情况下会有 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