Reputation:
I need to write a recursive function sums_to(nums, k) that takes a list of integers and returns True if the sum of all the elements in the list is equal to k and returns False otherwise.
I can't use sum function in any form, nor sum the list and then at the end check whether it equals k. In addition, I have to write sums_to as a single recursive function.
So far I have this:
def sums_to(nums, k):
if nums == []:
if k == 0
return True
return 0
else:
return nums[0] + sums_to(nums[1:], k) == k
Upvotes: 0
Views: 501
Reputation: 236114
Your approach doesn't seem correct, in particular the recursive step isn't right - you have to decrease the expected k
value until we reach the end of the list (and only test k
at this point!), instead of adding/comparing at each point of the list. Also, the base case is missing something - what happens if k
is not zero? you should return False
, not 0
. Better try this:
def sums_to(nums, k):
if nums == []:
return k == 0
else:
return sums_to(nums[1:], k - nums[0])
It works as expected:
sums_to([1, 2, 3, 4, 5], 14)
=> False
sums_to([1, 2, 3, 4, 5], 16)
=> False
sums_to([1, 2, 3, 4, 5], 15)
=> True
Upvotes: 3