Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have a function findsum(s,g) and I want to find whether elements in
s:list
can be the sum of any numbers in
g: list
or not... so for instance, if
s = [0,2,3,4,5]
,
g = [1,2,3]
,
the output should return
[False, True, True, True, True]
...
Explaination:
So 0 is false because nothing in g equals to or adds up to 0
2 is true because g contains a 2
3 is true because 2 and 1 in g adds up to 3
4 is true because if we add 2 to itself, 4 is the result
5 is also true because if we add 2 and 3 from g, we get 5

What I have tried:

def findsum(s,g):
    for f in g:
        for x in s:
           if sum (x) == f:
              return True
           else:
              return False
Posted
Comments
Richard MacCutchan 12-Dec-21 7:10am    
You are trying it the wrong way round. You need to create a new list which contains all possible sums from the numbers in g. So in the case above it would be [1, 2, 3, 1 + 2, 1 + 3, 2 + 3] = [1, 2, 3, 3, 4, 5], and removing the duplicate(s) gives [1, 2, 3, 4 ,5]. You can then use those values to find matching numbers in s.
0x01AA 12-Dec-21 12:58pm    
Hard to upvote this as long as it remains a comment ;)
Richard MacCutchan 13-Dec-21 4:22am    
That's OK, and it still needs testing by OP.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900