LearnFrenzy
Sign in Take a free test

Lambda Functions · Lambda Functions Coding Problems · Question 9

Compose several functions into one with lambdas in Python Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write compose(*funcs) that returns a function applying the given functions from right to left, and use it to clean user names.

Solution
main.py Run
from functools import reduce

def compose(*funcs):
    return reduce(lambda f, g: lambda x: f(g(x)), funcs, lambda x: x)

clean = compose(str.title, lambda s: " ".join(s.split()), str.strip)
for raw in ["  asha   rao ", "RAVI  kumar", "meera"]:
    print(repr(clean(raw)))

Output Verified by running it on Python 3

'Asha Rao'
'Ravi Kumar'
'Meera'

reduce chains the functions into one: strip first, then collapse inner spaces, then title-case. The identity lambda is the starting value.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links