2

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

2
  • 1
    Why do you think you need reduce at all? Commented Jan 6, 2016 at 17:52
  • @bereal it's also demanded, forgot to mention that. Either reduce, filter or map Commented Jan 6, 2016 at 17:57

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.