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 Lambda 2

mattamorphic
PLUS
mattamorphic
Courses Plus Student 6,641 Points

Functional Python : Lambdas

The challenge for the lambdas and finding the longest string seems to have issues - the code works on my local python terminal but not in the challenge box. Am I missing something?

strings.py
from functools import reduce

strings = [
    "Do not take life too seriously. You will never get out of it alive.",
    "My fake plants died because I did not pretend to water them.",
    "A day without sunshine is like, you know, night.",
    "Get your facts first, then you can distort them as you please.",
    "My grandmother started walking five miles a day when she was sixty. She's ninety-seven know and we don't know where she is.",
    "Life is hard. After all, it kills you.",
    "All my life, I always wanted to be somebody. Now I see that I should have been more specific.",
    "Everyone's like, 'overnight sensation.' It's not overnight. It's years of hard work.",
]

longest = reduce(lambda a, b : a if len(a) > len(b) else b, [string for string in strings])

1 Answer

akak
akak
29,445 Points

Hi Matt,

You don't have to do "string for string in strings". Reduce gets a string - uses lambda to compare, holds on the longer one . Then it takes another string, uses lambda to compare with the previous - takes longer one. Then another, compares with previous and so on.

( at least this is how I understand inner working of reduce. Fact that it passes the challenge seems to confirm it :) )

longest = reduce(lambda a,b: a if len(a) > len(b) else b, strings)
Max Hirsh
Max Hirsh
16,773 Points

Yup! I think that is pretty much how reduce works. It just works its way through an iterable without the need to add any for-loop syntax.