Explanation Of List Comprehensions
I'm attempting to learn about dynamic programming and recursion for Python 3.x. The code below is a simple example from my textbook: def recMC(coinValueList, change): minCoins
Solution 1:
for i in [c for c in coinValueList if c <= change]:
is the same as:
coins = []
for c in coinValueList:
if c <= change:
coins.append(c)
for i in coins:
#do your stuff
the list comprehension is much easier to code and better to read.
list comprehension is the "python-way".
Solution 2:
let me explain
[c for c in coinValueList if c <= change]
create new list with values from coinValueList
which are less than change
inside
After this You iterate over new list.
N.B. If You insist on using comprehension there Consider generator statement It will work same way but without memory consumption.
so result for loop should be not
for i in c:
for c in coinValueList:
if c<= change:
but
for i in coinValueList:
if i<= change:
Post a Comment for "Explanation Of List Comprehensions"