为什么我对两个和问题的答案在[3,2,3]中失败?

  • 本文关键字:答案 失败 问题 两个 python
  • 更新时间 :
  • 英文 :


不明白为什么这段代码以[3,2,3]作为输入失败。我的代码无法识别最后一个"3"的索引。在列表中,不知道该改什么

def twoSum(nums = [3, 2, 3], target = 9):
count = 0
target_i = []
for index, num in enumerate(nums):
for i in nums:
for j in nums:
if i + j == target and nums.index(i) != nums.index(j):
count += 1    
if count == 1:  
target_i.append(nums.index(i))
target_i.append(nums.index(j))

return target_i
print(twoSum())

您应该要求index函数搜索之后的第二个数字第一个,通过给它起始索引作为第二个参数。而且,你调用你的函数没有参数,默认参数没有解决方案,所以难怪你找不到一个。

整个东西更干净,也使用列表显示(不是文字),代码基于Barman's:

def twoSum(nums = [3, 2, 3], target = 6):
for i, num1 in enumerate(nums):
for num2 in nums[i+1:]:
if num1 + num2 == target:
return [i, nums.index(num2, i + 1)]

与酒吧经理的基准:

small default case:
620 ns   633 ns   634 ns   647 ns   658 ns  twoSum_Barry_Manilow
564 ns   570 ns   579 ns   588 ns   595 ns  twoSum_Right_Said_Fred
n=5000 case:
1091 ms  1093 ms  1095 ms  1098 ms  1125 ms  twoSum_Barry_Manilow
734 ms   735 ms   736 ms   737 ms   741 ms  twoSum_Right_Said_Fred

基准代码(在线试用!):

from timeit import repeat
def twoSum_Barry_Manilow(nums = [3, 2, 3], target = 6):
for i, num1 in enumerate(nums):
for j, num2 in enumerate(nums[i+1:], i+1):
if num1 + num2 == target:
return [i, j]
def twoSum_Right_Said_Fred(nums = [3, 2, 3], target = 6):
for i, num1 in enumerate(nums):
for num2 in nums[i+1:]:
if num1 + num2 == target:
return [i, nums.index(num2, i + 1)]
funcs = twoSum_Barry_Manilow, twoSum_Right_Said_Fred
for func in funcs:
print(func())
print()
print('small default case:')
for func in funcs:
number = 100000
times = sorted(repeat(func, number=number))
print(*('%4d ns ' % (t / number * 1e9) for t in times), func.__name__)
print()
print('n=5000 case:')
n = 5000
nums = list(range(n - 2)) + [-1, -1]
nums = list(range(n))
for func in funcs:
times = sorted(repeat(lambda: func(nums, -2), number=1))
print(*('%4d ms ' % (t * 1e3) for t in times), func.__name__)
print()

nums.index()总是返回第一次出现的索引,因此您无法获得第二个3的索引。在两个循环中使用enumerate(并且您根本不需要外部循环)。

如果要确保两个索引不相同,则在外部循环的当前元素之后开始内循环。

def twoSum(nums = [3, 2, 3], target = 9):
for i, num1 in enumerate(nums):
for j, num2 in enumerate(nums[i+1:], i+1):
if num1 + num2 == target:
return [i, j]

不需要count变量,因为只要找到第一个匹配的和就会返回。你可以让你要返回的列表是一个字面量,而不是追加到列表。

最新更新