3

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) )
1
  • can you share how snds look like when you print it or full code how you populating the snds Commented Jul 18, 2014 at 6:45

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I always mistake the lambda x,y as 2 elements from the list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.