Python Forum

Full Version: List of square roots python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So the question is:

I have to do a little program where the function receives a argument x, who is an integer and returns a list of the sum of the first n square roots.

Like [sqrt(1), sqrt(1) + sqrt(2), sqrt(1) + sqrt(2) + sqrt(3), ....]

I've made this line of code but it is just returning the sum
 return sum([x**0.5 for x in range(n+1)])
To get the cumulative sums of a list of length n:
[sum(the_list[:index]) for index in range(1, n+1)]
One problem is that your list is n+1 long. That's because you're including the square root of zero.
(Apr-06-2017, 01:39 AM)ichabod801 Wrote: [ -> ]To get the cumulative sums of a list of length n:
[sum(the_list[:index]) for index in range(1, n+1)]
One problem is that your list is n+1 long. That's because you're including the square root of zero.

And what is 'the_list' ?
The only thing that the function receives is an integer number (n).
It returns what you want.

Here is the sum of the list without any additional math:

>>> sum([x for x in range(11)])
55
Here is the sum of list's elements with x**0.5 applied on each of them
>>> sum([x**0.5 for x in range(11)])
22.4682781862041
Notice the result?
(Apr-08-2017, 08:33 PM)py7 Wrote: [ -> ]And what is 'the_list'

The list of square roots that you've already generated.
(Apr-08-2017, 09:39 PM)ichabod801 Wrote: [ -> ]1
[sum(the_list[:index]) for index in range(1, n+1)]

it only returns a list --> [0,0,0]
Output:
>>> the_list = [1, 2, 3] >>> n = 3 >>> [sum(the_list[:index]) for index in range(1, n+1)] [1, 3, 6]
The cumulative sums of the items in the list. That's what you're homework is asking for, just with square roots, not integers.