Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Functional Python The Lambda Lambada Reduce

James N
James N
17,864 Points

Think i have it, but don't know what to do with reduce()

I've been working on this code challenge for some time now, but i'm stuck!

Here's my error (what i get when i run it in a general workspace):

error.txt
Traceback (most recent call last):           
  File "Untitled.py", line 17, in <module>   
    print(list(total))                       
  File "Untitled.py", line 13, in product_sales                                           
    return twomemtup[0] * twomemtup[1]       
TypeError: 'float' object is not subscriptable    

Here's my code:

prices.py
from operator import add
from functools import reduce

prices = [
    (6.99, 5),
    (2.94, 15),
    (156.99, 2),
    (99.99, 4),
    (1.82, 102)
]

def product_sales(twomemtup):
  return twomemtup[0] * twomemtup[1]

total = map(product_sales, reduce(add, prices))

(in the variation on the workspace, i add:)

print(list(total))

Thanks for your help in advance.

PS: the treehouse code challenge engine says:

 Bummer! total isn't the right amount.

3 Answers

Steven Parker
Steven Parker
231,268 Points

You nearly had it. You just need to map first, and then reduce:

total = reduce(add, map(product_sales, prices))
Seth Kroger
Seth Kroger
56,413 Points

You have map and reduce reversed. Since reduce reduces a collection into a single value, and you are trying to find a sales total from individual sales, it should be the outermost function.

total = reduce(add, map(product_sales, prices))
James N
James N
17,864 Points

Thanks! since both of you responded on the same day, i don't know who to give best answer!

I though i was doing it first!

man, i'm dumb!