首页 > 解决方案 > 为什么我对二和问题的回答以 [3,2,3] 失败?

问题描述

无法弄清楚为什么此代码以 [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())

标签: python

解决方案


您应该要求该函数在第一个数字之后index搜索第二个数字,方法是将起始索引作为第二个参数。此外,您在没有参数的情况下调用您的函数,而默认参数没有解决方案,所以难怪您没有找到解决方案。

整个事情更清洁,也使用列表显示(不是文字),基于 Barman 的代码:

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)]

基准与 Barman 的:

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()

推荐阅读