i want to do a simple list manipulation in python:
here is the way i did it using two for loops:
lst = []
coins = [1, 2, 5, 10, 20, 50, 100, 200]
maxi = 200
lst = lst + [0]*(maxi+5)
lst[0] = 1
for c in coins:
for i in range(c, maxi+2):
lst[i] += lst[i-c]
the above code gives me desired results, now i try to convert the two line loop into a one-liner
add = lambda i, c: lst[i] += lst[i-c]
[add(i, c) for i in range(c, maxi+1) for c in coins]
but i am getting an invalid syntax error, how can i pass the two variables c and i to lambda
and then manipulate the list at the two indexes.
Which is a more pythonic way of doing it?
Can anyone suggest shorter code?
I want to use only list comprehension. How can i implement the above code using list comprehension?
I think the double loop you have is perfectly fine — why do you want a shorter version?
The error you get is because you put a statement inside a lambda function, where only expressions are allowed. You could write this as a list comprehension — something like (untested)
but seriously — why should you? Apart from being obscure, it also creates a pointless long list of
Nonevalues.The only thing I’d change about your code is the initialisation of
lst, which is strangely spread out over three lines. The following line will be enough: