Mary09
Mary09

Reputation: 35

Python: list function and lambda expressions

So I need to make a function that sums the squares of the numbers up until n, using only a return.

I've tried:

    from functools import reduce

    def soma_quadrados(n):
        return sum(list(reduce(lambda x: x**2, list(range(1,n+1)))))

Which gives the error:lambda () takes 1 positional argument but 2 were given

I've also tried

    return sum(list(reduce(lambda x: x**2, n)))

Which gives the error: reduce() arg 2 must support iteration

What should I do? Thanks in advance

Upvotes: 2

Views: 2672

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121724

reduce() passes in two arguments: the result accumulated so far, and the next value. Your lambda doesn't accept the result argument (the first).

If you want to produce a sum of all the squares, use sum() with a generator expression:

sum(i ** 2 for i in range(1, n + 1))

or use map() to map integers to their square in place of the generator expression:

sum(map(lambda i: i ** 2, range(1, n + 1)))

If you must use reduce(), have it sum:

reduce(lambda r, i: r + i ** 2, range(1, n + 1), 0)

Upvotes: 4

Related Questions