This program will be ran through a Python 3 IDE Write a function subsetSum() tha
ID: 3680416 • Letter: T
Question
This program will be ran through a Python 3 IDE
Write a function subsetSum() that takes as input a list of positive numbers and a positive number target. Your function should return True if there are three numbers in the list that add up to target. For example, if the input list is [5, 4, 10, 20, 15, 19] and target is 38, then True should be returned since 4 + 15 + 19 = 38. However, if the input list is the same but the target value is 10, then the returned value should be False because 10 is not the sum of any three numbers in the given list.
Here is an example of how the function should work:
>>> subsetSum([5, 4, 10, 20, 15, 19], 38)
True
>>> subsetSum([5, 4, 10, 20, 15, 19], 10)
False
Explanation / Answer
def subsetSum(seq, target):
if len(subset(seq,target)[0]) >= 3:
return True
else:
return False
def subset(a, tgt):
res = []
lenght = 0
def find(arr, tgt, com=()):
if not arr:
return
if arr[0] == tgt:
res.append(com + (arr[0],))
else:
find(arr[1:], tgt - arr[0], com + (arr[0],))
find(arr[1:], tgt, com)
find(a, tgt)
return res
print subsetSum([5, 4, 10, 20, 15, 19], 38)
print subsetSum([5, 4, 10, 20, 15, 19], 10)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.