英文:
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 []
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论