对于 x 在 [列表] 中,不会在每次迭代中进行迭代。

huangapple go评论61阅读模式
英文:

For x in [list] does not iterate on each pass

问题

任务:在列表中找到两个值,使它们的和等于目标值。
问题:对于sums,每次经过后似乎没有递增。

    class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in nums:
            for x in nums:
                print(x)
                print(nums.index(x))
                sum = x + i
                print(sum)
                if sum == target and nums.index(x) != nums.index(i):
                    return [nums.index(x), nums.index(i)]

期望返回:[0, 1],但没有返回任何内容。
请帮忙。

英文:

Task: To find 2 values in a list which add up to make a target value.
Problem: for x in sums doesnt seem to increment after each pass.

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
    for i in nums:
        for x in nums:
            print(x)
            print(nums.index(x))
            sum = x + i
            print(sum)
            if sum == target and nums.index(x) != nums.index(i):
                return [nums.index(x), nums.index(i)]

Expected return: [0, 1] but does not return anything.
HELP.

答案1

得分: 0

你的循环应该迭代索引而不是列表的内容,这样一旦找到正确的组合,返回索引会更容易。另外,你的内部循环只需从外部循环当前的索引开始迭代到列表的末尾。这将避免重复相同的计算和意外加倍相同的索引。最后,如果找不到两个加起来等于目标的数字,你应该返回一个空列表。

你可以通过以下方式实现这个目标:

def twoSum(self, nums: List[int], target: int) -> List[int]:
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if target - nums[i] == nums[j]:
                return [i, j]
    return []
英文:

Your loops should be iterating the indexes rather than the contents of the list, this will make it easier to return the index once the correct combination is found. Additionally your inner loop only needs to iterate from the index that your outer loop is currently at to the end of the list. This will avoid repeating the same calculations and accidentally doubling the same index. Finally you should return an empty list if two numbers that add up to the target are never found.

You can achieve this with:

def twoSum(self, nums: List[int], target: int) -> List[int]:
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if target - nums[i] == nums[j]:
                return [i,j]
    return []

huangapple
  • 本文由 发表于 2023年5月30日 07:42:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定