I am new-ish to python and one thing that always confuses me is when code is smashed into 1 line. Take the following for example:
def how_sum(targert_sum, numbers):
table = [None] * (targert_sum + 1)
table[0] = []
for i in range(targert_sum):
if table[i] is not None:
numbers = [num for num in numbers if i + num <= targert_sum]
for num in numbers:
table[i + num] = table[i] + [num]
return table[-1]
The line that says numbers = [num for num in numbers if i + num <= targert_sum]
has me confused. I tried breaking it down such that it wasn't in 1 line as follows:
def how_sum(targert_sum, numbers):
table = [None] * (targert_sum + 1)
table[0] = []
for i in range(targert_sum):
if table[i] is not None:
for num in numbers:
if (i + num <= targert_sum):
numbers = [num]
for num in numbers:
table[i + num] = table[i] + [num]
return table[-1]
Can someone explain where I am going wrong and maybe explicitly write out the expanded nested for-if statements?
Edit: I thought it may be helpful to provide some problem context. I am trying to solve the "how sum" problem while I am self-learning some algorithms. The goal is to have some target number (ex 7) and a list (ex [2, 3]) and check how the elements of the list can add to 7 (so [2, 2, 3])