gpt4 book ai didi

python - 2 和问题 : given an unsorted list of ints, 查找两个元素的总和是否等于给定目标。如何让我的代码更 Pythonic?

转载 作者:行者123 更新时间:2023-12-05 07:11:23 29 4
gpt4 key购买 nike

我正在尝试了解 PEP-8 指南、编写 Pythonic 代码和 Python 的标准库(我已经踏入这段旅程的一天)。使以下代码(包括注释)更符合 Pythonic 的建议将不胜感激。我知道算法可以改进,但这不是目前的优先事项 - 但如果你有一个优雅的解决方案,请写下来!

我已经通过以下 PEP-8 检查器运行它,所以希望基础知识不是问题:http://pep8online.com/checkresult

import collections


def two_sum(input_list, target):
# Determine if two elements in list add to target
# dict_of_counts - key: element from input_list, value: count of element
dict_of_counts = collections.Counter(input_list)
for key in dict_of_counts:
complement_key = target - key
if complement_key in dict_of_counts:
# Corner case: complement_key is the same as key,
# but the count is one (so threat of a false +ve)
if complement_key != key:
return(True)
elif dict_of_counts[complement_key] > 1:
return(True)
return(False)

附言我的第一个问题:噢!

最佳答案

如果您想提高 PEP-8 技能,我强烈建议您使用 linter,例如 flake8 .它非常适合发现任何违反 PEP-8 的行为,当您尝试让 flake8 开心时,您会边走边了解所有细节。

关于python - 2 和问题 : given an unsorted list of ints, 查找两个元素的总和是否等于给定目标。如何让我的代码更 Pythonic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60787162/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com