List of square roots

2

How can I make a function that receives a n parameter, which returns a list of the first% of% square roots using higher order functions in Python.

As shown below:

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

I've tried to do it this way:

return sum([x**0.5 for x in range(1,n+1)])

But do not give me what I want, give me just the sum of% root_.

    
asked by anonymous 08.04.2017 / 22:08

2 answers

3

sum is not required to return the list, simply do

import math

def raiz(n):
  return [math.sqrt(x) for x in range(1, n + 1)]

print (raiz(6))
# [1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178]

DEMO

Another alternative with map :

def raiz(n):
  return list(map(math.sqrt, range(1, n + 1)))
    
09.04.2017 / 00:13
1

Here is the answer to what I understood from the question, by the text fragment placed in the question:

  

As shown below:   [sqrt (1), sqrt (1) + sqrt (2), sqrt (1) + sqrt (2) + sqrt (3), ...]

It is clear that the expected result would be a list in which each element is the result of the root of element n added to the results of the roots of each previous n, so the result for a range of 1 to 4 would be: >

[1.0, 2.414213562373095, 4.146264369941973, 6.146264369941973]

Where, the first element is the root of 1, the second is the sum of the root of 1 plus the root of 2, the third, the sum of the root of 1 + the root of 2 + the root of 3, and finally the last would be the sum of the first 3 elements + the root of 4, or the last element would be exactly the result of the first attempt expressed in the text of the question:

return sum([x**0.5 for x in range(1,n+1)])

If n is equal to 4 the expected result (according to the text) would have to be:

[1.0, 2.414213562373095, 4.146264369941973, 6.146264369941973] 

Taking this approach into consideration, I developed 2 functions, one without the use of high-order functions and the other using them.

Below the code where the map function combined with lambda is used:

# Utilizando Funcoes de alta ordem
def sum_sqr_high(n,dt):
    current = sqrt(n)+dt['last']
    dt['list_sqr'].append(current)
    dt['last'] = current

data = {'last': 0, 'list_sqr': []}
list(map(lambda n: sum_sqr_high(n, data), [n for n in range(1,5)]))

print ('Com alta ordem ',data['list_sqr'])    
Com alta ordem  [1.0, 2.414213562373095, 4.146264369941973, 6.146264369941973]

Below the code without the use of high order functions:

# Sem alta orde
def sqrn(_n):
    last=0
    list_sqr = []
    for n in range(1, _n+1):
        current = sqrt(n)+last
        list_sqr.append(current)
        last = current
    return list_sqr 

print('Sem alta ordem: ',sqrn(4))
Sem alta ordem:  [1.0, 2.414213562373095, 4.146264369941973, 6.146264369941973]

Click to see rolled code

    
09.04.2017 / 01:59