Python如果......和超出界限的错误没有意义?

时间:2017-06-29 22:44:42

标签: python

我做了一个有趣的DFS解决方案,但一直困扰我的是,通常如果你有一个if ...和语句,Python将在第一个语句为False后停止检查。在这种情况下,如果我将两个语句放在一起,我会得到一个超出范围的索引。

例如,这很好用

if not nums:
    if s[i]=='I' and (path[i]<path[i+1]) or (s[i]=='D' and path[i]>path[i+1]):
           ret=min(ret, path)

但我会收到错误:

if not nums and if s[i]=='I' and (path[i]<path[i+1]) or (s[i]=='D' and path[i]>path[i+1]):
     ret=min(ret, path)

有人能发现我看不到的东西吗?

class Solution(object):
    def findPermutation(self, s):
        """
        :type s: str
        :rtype: List[int]
        """

        def dfs(ret,nums,i,path):
            if not nums:
                if s[i]=='I' and (path[i]<path[i+1]) or (s[i]=='D' and path[i]>path[i+1]):
                    ret=min(ret, path)
            for j in xrange(len(nums)):
                if len(path)>1:
                    if (s[i]=='I' and path[i]>path[i+1]) or (s[i]=='D' and path[i]<path[i+1]):
                        return ret
                    ret=dfs(ret,nums[:j]+nums[j+1:],i+1,path+[nums[j]])
                else:
                    ret=dfs(ret,nums[:j]+nums[j+1:],i,path+[nums[j]])
            return ret
        return dfs([len(s)+3],range(1,len(s)+2),0,[])

1 个答案:

答案 0 :(得分:2)

使用额外的if似乎只是一个语法错误,使用:

if not nums and

而不是

if not nums and if