python all()

all(*iterable*)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable): 
    for element in iterable: 
        if not element: 
             return False 
    return True

https://leetcode.com/problems/matchsticks-to-square/#/description

class Solution(object):
    def makesquare(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        nums = sorted(nums, reverse=True)
        sum_ = sum(nums)
        if not nums or len(nums) < 4 or any(num > sum_ // 4 for num in nums):
            return False
        if sum_ % 4 != 0:
            return False
        return self.dfs(nums, [0]*4, sum_ // 4)

    def dfs(self, nums, sides, target):
        if not nums:
            if all(side == target for side in sides): # all()
                return True
            else:
                return False
        for i in range(4):
            if sides[i] + nums[0] > target:
                continue
            sides[i] += nums[0]
            if self.dfs(nums[1:], sides, target):
                return True
            sides[i] -= nums[0]
        return False
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,394评论 0 23
  • 早晨第一节,数学学了节新课,认识时和分,为了让孩子们感受一分钟有多长,做了ppt,开始只是让孩子们直观的去看...
    皮_小皮阅读 1,709评论 0 10
  • 当我一次次的回忆 都有他的部伴 是记忆留下的影子 守候着梦的成长 你在哪! 我在这里一直等你的出现! 是泪水把我从...
    狂野的青春阅读 1,924评论 0 0
  • C姑娘从来没想过离开L先生会这么痛苦,痛苦的都想要死掉,甚至去查怎样可以死的轻松一点,不要那么痛苦。因为这段感情带...
    C丶陌小陌阅读 1,618评论 0 1