简体   繁体   English

Python中关于局部变量范围的问题

[英]A question about local variable, range, for in Python

I am solving an algorithm problem in https://leetcode.com/problems/two-sum .我正在解决https://leetcode.com/problems/two-sum 中的算法问题。

Here is my code:这是我的代码:

class Solution:
    def twoSum(self, nums, target):
        list_length = len(nums)
        result = list()
        for i in range(0, list_length):
            for j in range(i+1, list_length):
                s = i + j
                if s == target:
                    result.append(i)
                    result.append(j)
                    return result

s = Solution()
ts = s.twoSum([2, 7, 11, 15], 9)
print(ts)

The output is None .输出是None

I want to know why is it None rather than [0,1] .我想知道为什么它是None而不是[0,1]

When calculating s you are summing the indeces ( i and j ) you are iterating through rather than the elements at those indeces.在计算s您正在对迭代的 indeces( ij )求和,而不是对这些 indeces 处的元素进行求和。 This works:这有效:

class Solution:
    def twoSum(self, nums, target):
        list_length = len(nums)
        result = list()
        for i in range(list_length):
            for j in range(1, list_length):
                s = nums[i] + nums[j]
                if s == target:
                    result.append(i)
                    result.append(j)
                    return result
s = Solution()
ts = s.twoSum([2, 7, 11, 15], 27)
print(ts)

Indentation is important, and both i and j references are to the index within the list of nums example, [0,3,4] so num[0] is 0 etc. etc. And it's a good habit to use a main method at the bottom although not necessary depending on what you are doing.缩进很重要, ij引用都指向nums示例列表中的索引,[0,3,4] 所以 num[0] 是 0 等等。并且在以下位置使用 main 方法是一个好习惯底部虽然不是必需的,这取决于您在做什么。 Hope this helps..希望这可以帮助..

class Solution:

   def twoSum(self, nums, target):
      list_length = len(nums)
      # actually use the list() functionality here not 'list()'but '[]'
      result = []
      for i in range(list_length):
         for j in range(1, list_length):
            s = nums[i] + nums[j]
            if s == target:
              result.append(i)
              result.append(j)
              return result


if __name__ == "__main__":
  #use a main method if possible
  s = Solution()
  ts = s.twoSum([2, 7, 11, 15], 9)
  print(ts)

I personally find a couple things that your code could do better.我个人发现您的代码可以做得更好的几件事。 First there's nothing in your class as it isn't indented.首先,您的课程中没有任何内容,因为它没有缩进。 Second I find the append method to be tedious.其次,我发现 append 方法很乏味。 You can initialize a list a with a = [""]* length where this will a create a list a with a specified length.您可以使用a = [""]* length初始化列表 a,这将创建一个具有指定长度的列表 a。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM