Search code examples
pythonfor-loopnestedlist-comprehensionone-liner

Python One Line For Loop With If: Please Explain?


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])


Solution

  • A list comprehension is equivalent to appending to the result variable.

    But the result variable has to start as an empty list. Since your result variable is the same as the variable you're iterating over, you need to use a different variable for the result, then you can copy it to the original variable (this is essentially what happens internally in the list comprehension).

    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:
                result = []
                for num in numbers:
                    if (i + num <= targert_sum):
                        result.append(num)
                numbers = result
                for num in numbers:
                    table[i + num] = table[i] + [num]
        return table[-1]