does anybody knows why this function doesn´t work very well:

f=lambda n: reduce(lambda x,y:x**2+y**2, map(int,str(n)))

I want that this function add the square of the digits of a number

an example of what i want:

f(442)=4**2+4**2+2**2=36 and it's giving me f(442)=1028!!!:S

However fou numbers with 2 digits the function works!

10 Years
Discussion Span
Last Post by Ene Uran

First, the newer Python constructions pretty much eliminate the need for "map()".

Try this:

squaredigits = lambda x: sum([int(i)*int(i) for i in x])



Jeff's suggestion is modern Python. Make sure that your number is iterated as string:

squaredigits = lambda x: sum([int(i)*int(i) for i in str(x)])

print squaredigits(442)  # -->  36

Note: filter(), map() and reduce() will go away with Python30

# add this to future code
try: filter and map and reduce
    def filter(f, s): return [x for x in s if f(s)]
    def map(f, *s): return [f(*x) for x in zip(*s)]
    def reduce(f, s, i=None):
        r = i
        for x in s:
            r = f(r, x)
        return r

Part of the reason is that list comprehensions are simply so much faster than using defined function call. Also reduce() isn't used much. Good news is that lambda will stay.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.