I don’t understand how the space complexity is being calculated.
Here is the code with my code comments (in caps so they stick out)
def make_table2(N):
table = [] #DOES THIS COUNT AS N?
for _ in range(N):
row = [] #DOES THIS COUNT AS N?
for _ in range(N):
row.append([1 for _ in range(N)]) #I HAVE NO IDEA ABUT THIS. I THOUGHT IT WOULD BE 1 BECAUSE WE ARE USING ONLY ONE NUMBER. IS THIS THE NESTED LIST?
table.append(row)
return table
I thought it would N^2 but it is N^3 and I don’t know how that is calculated.
While the row.append() operation will be a constant, the list comprehension is still linear depending on N.
The above can be re-written as -
for _ in range(N):
row_2 = []
for _ in range(N):
row_2.append(1)
row.append(row_2)
That’s still 3 nested for loops.
Note While you can re-write the list comprehension into the above for loop, the list comprehension is still a bit faster than the for loop equivalent. I am just expanding it to help you better understand the breakdown.
Hi @the_doctor,
Thank you for breaking this out (or down?) it helped a lot. I can see where we get N^3 now. Just another question. I wasn’t focusing on the for-loops originally. I was focusing on the variables that were assigned the empty lists (i.e., table and row) for N. Should I not be doing that in the future for space complexity?