Hello. There is the following task: using reduce (the choice fell on it, but perhaps this is not true) sum up the 1 / y relationship, where y is the list element

you can pre-perform a division operation and you will obviously:

pers_of_coef = reduce((lambda x, y: x + y), coef_arr) 

but I would like to fit all in one line. The following expression does not work correctly:

 pers_of_coef = reduce((lambda x, y: x + (1/y)), coef_arr) 

As I understand it, in this solution x is the first element, and it is not normalized (1 / x), as a result there is an option to insert a 0 position on the list zero, but this option also does not seem optimal.

    1 answer 1

     In [356]: lst Out[356]: [67, 11, 72, 39, 3, 20, 71, 66, 33, 4, 34, 92, 69, 52, 72, 4, 42, 93, 43, 13] In [357]: sum(1./y for y in lst) Out[357]: 1.3108716089277184 

    better use numpy:

     In [349]: import numpy as np In [350]: a = np.random.randint(1, 100, size=(20)) In [351]: a Out[351]: array([67, 11, 72, 39, 3, 20, 71, 66, 33, 4, 34, 92, 69, 52, 72, 4, 42, 93, 43, 13]) In [352]: 1./a Out[352]: array([0.01492537, 0.09090909, 0.01388889, 0.02564103, 0.33333333, 0.05 , 0.01408451, 0.01515152, 0.03030303, 0.25 , 0.02941176, 0.01086957, 0.01449275, 0.01923077, 0.01388889, 0.25 , 0.02380952, 0.01075269, 0.02325581, 0.07692308]) In [355]: np.sum(1./a) Out[355]: 1.3108716089277184