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?

Viewed 62

I'm trying to learn about PEP-8 guidelines, writing Pythonic code, and about Python's standard libraries (am a day into this journey). Suggestions to make the following piece of code (including comments) more Pythonic would be much appreciated. 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

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)

P.S. My first question ever : O !

2 Answers

If you want to improve your PEP-8 skills, I highly recommend using a linter such as flake8. 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.

from typing import List, Tuple

if complexity is not an issue the most pythonic way (for me) is:

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
Related