Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python reduce issue object has no attribute

Tags:

python

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) )
like image 959
zinking Avatar asked Dec 08 '25 09:12

zinking


1 Answers

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)
like image 82
Dunes Avatar answered Dec 09 '25 21:12

Dunes