679. 24 Game

来源:互联网 发布:网站建设软件下载 编辑:程序博客网 时间:2024/06/03 23:27

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: TrueExplanation: (8-4) * (7-1) = 24

Example 2:

Input: [1, 2, 1, 2]Output: False

Note:

  1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
  2. 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.
  3. 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

直接暴力枚举

from itertools import permutationsclass 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


原创粉丝点击