snds is a collection of nodes , which has the attribute of 'alloc'. the following two statements looks equivalent to me, but the first throw error AttributeError: 'int' object has no attribute 'alloc'
I might have made some stupid mistake some where which I can't discover.
#return reduce( lambda x,y:x.alloc+y.alloc, snds)
return reduce( lambda x,y:x+y, map( lambda x:x.alloc, snds) )
The function that reduce takes has two parameters. Once is the current element being processed and the other is the accumulator (or running total in this instance).
If you were to write out your reduce as a loop this is what it would look like.
x = 0
for y in snds:
x = x.alloc + y.alloc
What's wrong here is that the running total will always be an int and not a node, so it never has the attribute alloc.
The correct loop would look like
x = 0
for y in snds:
x = x + y.alloc
Which, if using reduce would look like.
total = reduce((lambda total, item: total+item.alloc), snds)
However, an even better way to do this would be to use sum and a generator.
total = sum(item.alloc for item in snds)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With