简体   繁体   中英

Checking if a number is the sum of 2 other numbers

Problem Statement

Given a list of numbers and a number k , return whether any two numbers from the list add up to k .

Example

Given [1, 2, 3] and k = 5 , return True since 2 + 3 = 5 .

This is what I've tried to do:

def pairs(n):
    for i in range(len(n)):
        for j in range(i+1, len()):
            yield n[i], n[j]


def ListCheck():
    number = input("Give me a number:")
    val = int(number)
    nums = [1,2,3]
    for i, j in pairs(nums):
        if j + i == val:
            print(True)
            break


ListCheck()

I'm getting an error when I run it, and I can't understand why.

You could also do itertools.combinations , little shorter than @bitto's solution:

import itertools
def f(lst,num):
    for x,y in itertools.combinations(lst,2):
        if x+y==num:
            return True
    return False
lst=[1,2,3]
num=int(input("Give me a number: "))
print(f(lst,num))
def issumoftwo(lst,num):
    for x in lst:
        for y in lst:
            if x+y==num and lst.index(x)!=lst.index(y):
                return True
    return False
lst=[1,2,3]
num=int(input("Give me a Number: "))
print(issumoftwo(lst,num))

Output

Give me a number: 5
True

You misses an n inside len() . The error

TypeError: len() takes exactly one argument (0 given)

tells you exactly what is wrong (if you fix the indentation problems of your code postet above).


You can streamline your code by using itertools.combinations . If you add some parameters to a function, you can generalize the problem searching as well - to get all combinations of n numbers from your list that add up to your targetvalue.

from itertools import combinations 

def is_sum_of_n_numbers(data ,target_value, num_elem):
    """Returns 'True' if any combinatin of 'num_elem'ents 
    from 'data' sums to 'target_value'"""
    return any(sum(x)==target_value for x in combinations(data, num_elem))

def find_sum_in_combination(data, target_value, num_elem):
    """Returns all combinations of 'num_elem'ent-tuples from 'data' 
    that sums to 'target_value'"""
    return [x for x in combinations(data,num_elem) if sum(x) == target_value]

Get all of them:

d = [1,2,3,4,5]
for numbers in range(1,6):
    for s in range(1,sum(d)+1):
        result = find_sum_in_combination(d,s,numbers)
        if result:
            print(f"Sum {s} from {d} with {numbers} numbers: ", result)

Output:

Sum 1 from [1, 2, 3, 4, 5] with 1 numbers:  [(1,)]
Sum 2 from [1, 2, 3, 4, 5] with 1 numbers:  [(2,)]
Sum 3 from [1, 2, 3, 4, 5] with 1 numbers:  [(3,)]
Sum 4 from [1, 2, 3, 4, 5] with 1 numbers:  [(4,)]
Sum 5 from [1, 2, 3, 4, 5] with 1 numbers:  [(5,)]
Sum 3 from [1, 2, 3, 4, 5] with 2 numbers:  [(1, 2)]
Sum 4 from [1, 2, 3, 4, 5] with 2 numbers:  [(1, 3)]
Sum 5 from [1, 2, 3, 4, 5] with 2 numbers:  [(1, 4), (2, 3)]
Sum 6 from [1, 2, 3, 4, 5] with 2 numbers:  [(1, 5), (2, 4)]
Sum 7 from [1, 2, 3, 4, 5] with 2 numbers:  [(2, 5), (3, 4)]
Sum 8 from [1, 2, 3, 4, 5] with 2 numbers:  [(3, 5)]
Sum 9 from [1, 2, 3, 4, 5] with 2 numbers:  [(4, 5)]
Sum 6 from [1, 2, 3, 4, 5] with 3 numbers:  [(1, 2, 3)]
Sum 7 from [1, 2, 3, 4, 5] with 3 numbers:  [(1, 2, 4)]
Sum 8 from [1, 2, 3, 4, 5] with 3 numbers:  [(1, 2, 5), (1, 3, 4)]
Sum 9 from [1, 2, 3, 4, 5] with 3 numbers:  [(1, 3, 5), (2, 3, 4)]
Sum 10 from [1, 2, 3, 4, 5] with 3 numbers:  [(1, 4, 5), (2, 3, 5)]
Sum 11 from [1, 2, 3, 4, 5] with 3 numbers:  [(2, 4, 5)]
Sum 12 from [1, 2, 3, 4, 5] with 3 numbers:  [(3, 4, 5)]
Sum 10 from [1, 2, 3, 4, 5] with 4 numbers:  [(1, 2, 3, 4)]
Sum 11 from [1, 2, 3, 4, 5] with 4 numbers:  [(1, 2, 3, 5)]
Sum 12 from [1, 2, 3, 4, 5] with 4 numbers:  [(1, 2, 4, 5)]
Sum 13 from [1, 2, 3, 4, 5] with 4 numbers:  [(1, 3, 4, 5)]
Sum 14 from [1, 2, 3, 4, 5] with 4 numbers:  [(2, 3, 4, 5)]
Sum 15 from [1, 2, 3, 4, 5] with 5 numbers:  [(1, 2, 3, 4, 5)]

Doku:

The logic of your code is correct (It's unnecessarily complex as you can see by comparing with the above answer, but still correct ;)....)
Just check your indentations and put for j in range(i+1, len(n)) in the 3rd line of your code...you forgot the 'n'!! You need to give atleast one argument to len .

You can solve your solution this way

n=[3,2,1]
number=int(input("Please enter nubmer"))
for i in n:
    num=number - i
    if num in n:
        print(num,i)
        break

This is solution but need to be customize as you want

simple checking (k - arrayValue) will not work because if k = 4 and there is one 2 in array - it will be false positive
so you need to exclude cheked values from further loops
it can be done with pop function for arrays

python solution:

def ListCheck():
    number = 11
    nums = [10, 15, 3, 7, 9, 6, 4, 8]
    found = 0
    while found == 0:
        if len(nums) < 2: # check if array has at least 2 numbers
            break
        while len(nums) > 1:
            comparenum = nums.pop() # removes comparable number from array to avoid false true if nums has item == number*2 
            if (number - comparenum) in nums:
                print(True)
                found = 1
                break

    if found == 0:
        print(False)
        

ListCheck()
exit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM