简体   繁体   English

2-sum 问题:给定一个未排序的整数列表,找出两个元素的总和是否为给定的目标。 如何让我的代码更 Pythonic?

[英]2-sum problem: given an unsorted list of ints, find if two elements sum to a given target. How to make my code more Pythonic?

I'm trying to learn about PEP-8 guidelines, writing Pythonic code, and about Python's standard libraries (am a day into this journey).我正在尝试了解 PEP-8 指南、编写 Pythonic 代码以及 Python 的标准库(这是此旅程的一天)。 Suggestions to make the following piece of code (including comments) more Pythonic would be much appreciated.让以下代码(包括注释)更加 Pythonic 的建议将不胜感激。 I know the algorithm could be improved, but this isn't a priority at the moment - but please do write if you have an elegant solution!我知道算法可以改进,但这不是目前的优先事项 - 但如果你有一个优雅的解决方案,请写!

I've run it through the following PEP-8 checker, so hopefully the basics are not a problem: http://pep8online.com/checkresult我已经通过以下 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)

PS My first question ever : O ! PS我的第一个问题:哦!

If you want to improve your PEP-8 skills, I highly recommend using a linter such as flake8 .如果您想提高您的 PEP-8 技能,我强烈建议您使用 flake8 之类的linter It is really good in finding any PEP-8 violations, and while you're trying to make flake8 happy you'll learn all the ins- and outs as you go.发现任何 PEP-8 违规行为非常好,当你试图让 flake8 开心时,你会在你去的过程中学习所有的细节。

from typing import List, Tuple

if complexity is not an issue the most pythonic way (for me) is:如果复杂性不是问题,最pythonic的方式(对我来说)是:

def pair_sum_v1(array: List[int], s: int) -> List[Tuple]:
    """
    :param array: list of integers
    :param s: sum
    :return: list of unique pairs [(a1,b1), (a2,b2)] where ai+bi=s
    """
    pair_sums = [(num, s - num) for idx, num in enumerate(array) if s - num in array[idx:]]
    return pair_sums

if you want to make it faster:如果你想让它更快:

def pair_sum_v2(array: List[int], s: int) -> List[Tuple]:
    """
    :param array: list of integers
    :param s: sum
    :return: list of unique pairs [(a1,b1), (a2,b2)] where ai+bi=s
    """
    explored_integers = []
    pair_sums = []

    for idx, num in enumerate(array):
        if num not in explored_integers:
            complement = s - num
            if complement in array[idx:]:
                pair_sums.append((num, complement))
                explored_integers.extend([num, complement])

    return pair_sums

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Pythonic方法检查列表中的不连续元素数量是否达到给定值 - Pythonic way of checking if indefinite # of consec elements in list sum to given value 给定 3 个列表,找出前两个列表中哪两个元素之和尽可能接近第三个列表中的每个值 - Given 3 lists, find which two elements in the first two lists sum as close as possible to each value in the third list 查找一个数字是否是给定集合中两个或更多个数字的可能总和--python - Find if a number is a possible sum of two or more numbers in a given set - python 给定数组的目标总和 - target sum for given array 返回总和为给定目标的列表中的数字 - Returning the numbers in a list whose sum is a given target 给定元素长度的Python子集总和问题 - Python Subset Sum Problem for Given Length of Elements 如果元素总和为给定数字,则追加到列表中 - appending in list if sum of elements makes given number 如何打印列表的元素,其总和等于 python 中的给定数字? - how to print elements of a list whose sum is equal to a given number in python? 如何制作一个递归函数,返回给定两个列表的相同索引的总和列表。? - How can I make a recursive function that returns a list of sum of the same index given two lists.? 找到给定两点的数据帧的曼哈顿总和 - find the manhatten sum of a dataframe given two points
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM