Here is the answer to what I understood of the question, by the text fragment posed 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 root results 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
is, 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 function map 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 the code running
"Using higher-order functions" is a constraint, a requirement or an option?
– Sidon
@Sidon What I am doing is a requirement, it is necessary to use the higher order functions
– py_9
@Sidon For the following how can I make a function that receives a function, a list and an element , return all intermediate states of the accumulator in the form of a list. That is, for example, a function(lambda Acum, x: Acum + x, [2, 4, 6], 0) -> [0, 2, 6, 12]
– py_9