Coding Challenges < Python >

What will be the output of this code?
def count_subsets(nums, target):
memo = {}

def backtrack(index, remaining):
if (index, remaining) in memo:
return memo[(index, remaining)]

if remaining == 0:
return 1
if remaining < 0 or index == len(nums):
return 0

count = backtrack(index + 1, remaining - nums[index]) + backtrack(index + 1, remaining)
memo[(index, remaining)] = count
return count

return backtrack(0, target)

nums = [1, 2, 3, 4, 5]
target = 7
print(count_subsets(nums, target))
def count_subsets(nums, target):
memo = {}

def backtrack(index, remaining):
if (index, remaining) in memo:
return memo[(index, remaining)]

if remaining == 0:
return 1
if remaining < 0 or index == len(nums):
return 0

count = backtrack(index + 1, remaining - nums[index]) + backtrack(index + 1, remaining)
memo[(index, remaining)] = count
return count

return backtrack(0, target)

nums = [1, 2, 3, 4, 5]
target = 7
print(count_subsets(nums, target))
Solution:
No , it’s 3 😌
Jump to solution
11 Replies
Marvee Amasi
Marvee Amasiβ€’5mo ago
It's 2 The function counts the number of subsets coming from the num array , which sums up to the target value . Which would definitely be 2
nour_oud
nour_oudβ€’5mo ago
Try again :pikawink:
Marvee Amasi
Marvee Amasiβ€’5mo ago
For reals? πŸ‘€
nour_oud
nour_oudβ€’5mo ago
yes yes yes
Marvee Amasi
Marvee Amasiβ€’5mo ago
But there are two subsets [1, 2, 4] and [3, 4] whose elements sum up to 7 , so it's 2
Solution
Camila_99$$
Camila_99$$β€’5mo ago
No , it’s 3 😌
Camila_99$$
Camila_99$$β€’5mo ago
{1, 2, 4}, {2, 5}, and {3, 4}.
nour_oud
nour_oudβ€’5mo ago
You're only missing one
Marvee Amasi
Marvee Amasiβ€’5mo ago
I was that close
nour_oud
nour_oudβ€’5mo ago
yeah πŸ˜… ✨
Marvee Amasi
Marvee Amasiβ€’5mo ago
Brilliant
Want results from more Discord servers?
Add your server