You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *
, /
, +
, -
, (
, )
to get the value of 24.
Example 1:
Input: [4, 1, 8, 7] Output: True Explanation: (8-4) * (7-1) = 24
Example 2:
Input: [1, 2, 1, 2] Output: False
Note:
- The division operator
/
represents real division, not integer division. For example, 4 / (1 - 2/3) = 12. - Every operation done is between two numbers. In particular, we cannot use
-
as a unary operator. For example, with[1, 1, 1, 1]
as input, the expression-1 - 1 - 1 - 1
is not allowed. - You cannot concatenate numbers together. For example, if the input is
[1, 2, 1, 2]
, we cannot write this as 12 + 12.
http://wiki.jikexueyuan.com/project/explore-python/Standard-Modules/itertools.html
直接暴力枚举,先确定数字排放顺序,然后决定计算顺序,然后决定2个数之间的计算方式
from itertools import permutations
class Solution(object):
def judgePoint24(self, nums):
def f(s1, s2):
ret = []
for a in s1:
for b in s2:
ret.append('(' + a + '+' + b + ')')
ret.append('(' + a + '-' + b + ')')
ret.append('(' + b + '-' + a + ')')
ret.append('(' + b + '/' + a + ')')
ret.append('(' + b + '/' + a + ')')
ret.append('(' + b + '*' + a + ')')
return ret
strs = [str(float(num)) for num in nums]
for c in permutations(strs):
# 可以有2中结合方式
eq1 = f(f(f([c[0]], [c[1]]), [c[2]]), [c[3]])
eq2 = f(f([c[0]], [c[1]]), f([c[2]], ([c[3]])))
for eq in eq1+eq2:
try:
if 23.99 < eval(eq) < 24.01:
return True
except:
pass
return False