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

标签 python python-3.x idioms pep8

我正在尝试了解 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/

相关文章:

python - 强制 TkInter Scale slider 捕捉到鼠标

python - 对 Pandas 使用重采样和聚合时丢失字符串列

python-3.x - 删除/禁用PyQt5中的关闭按钮

python - 检查回文文本,忽略标点符号、空格和大小写

c++ - C++ 中的 min= 成语?

python - 使用 numba jit,Python 的段间距离

python - 将 gif 图像放入 tkinter 窗口

ruby - 更惯用的 ruby​​ 写法 @var = obj ['blah' ] 除非 obj ['blah' ].nil?

c++ - 如何使用类的常量裁判和非常量裁判版本避免 DRY?

python - 从自己的类调用 iPyWidgets 不显示