i have test list
a = [1,2,3,4,5,6,7,8,9,10]
for example, i want to squared some of them and get sum of them. then i want to divide this sum to 2
. and then i want raise to the power 1/4
code is:
result = ((a[0]**2+a[1]**2)/2)**(1/4)
prolbem is that i define each value. in this example its a[0]
and a[1]
i want just get some variable of number of iterable objects (in my case it's n = 2
)
for n = 3
its should be equal to:
((a[0]**2+a[1]**2+a[2]**2)/2)**(1/4)
i can get this values with
for i in range(3):
print(a[i])
with output:
1
2
3
but idk how to add them to my math operation code
This should do it:
square=0
for i in range(3):
square=square+a[i]**2
if i==2:
square=(square/2)**(1/4)
print(square)
This squares each number and adds it to the square
variable. If it is on the last iteration of i, it divides square
by 2 and raises it to the power of 1/4
You can create a dictionary of operations to perform and apply them on part of your list. this needs python 3.7+ to guarantee insert-order of rules in dict == order they get applied later:
a = [1,2,3,4,5,6,7,8,9,10]
# rules
ops = {"square_list" : lambda x: [a**2 for a in x], # creates list
"sum_list" : lambda x : sum(x), # skalar
"div_2" : lambda x : x/2, # skalar
"**1/4" : lambda x: x**(1/4)} # skalar
n_min = 0
for m in range(1,len(a)):
# get list part to operate on
parts = a [n_min:m]
print(parts)
# apply rules
for o in ops:
parts = ops[o](parts)
# print result
print(parts)
Output:
[1]
0.8408964152537145
[1, 2]
1.2574334296829355
[1, 2, 3]
1.6265765616977856
[1, 2, 3, 4]
1.9679896712654303
[1, 2, 3, 4, 5]
2.2899878254809036
[1, 2, 3, 4, 5, 6]
2.597184780029334
[1, 2, 3, 4, 5, 6, 7]
2.892507608519078
[1, 2, 3, 4, 5, 6, 7, 8]
3.1779718278112656
[1, 2, 3, 4, 5, 6, 7, 8, 9]
3.4550450628484315
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.