python - 为什么我对二和问题的回答以 [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())
解决方案
您应该要求该函数在第一个数字之后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()
推荐阅读
- docker - nomad 的工作如何从本地 docker 图像中获取
- node.js - 使用 WSL 在 VSCode 中使用 nodemon + babel-node 进行调试
- javascript - 登录后需要相互等待的多个 axios 调用,然后将用户重定向到 Vue.js 上的仪表板 [时间问题]
- javascript - 在 onsubmit 函数完成之前如何防止表单提交?
- sql - 查询以查找具有指定月份的帐户
- reactjs - Img 的来源应该是动态的
- php - 循环进入 CSV 文件并从头文件 PHP 中获取特定值
- python - 如何将 2D 数组“切片”成 3D 数组
- python - 在 Pandas 数据框中使用 groupby 和 shift 操作计算条件概率
- angular - Angular:如何在不更改模板路由的情况下更新 queryParams