i need to print a solution list for the input list using the below formula, this is the code:
sub=[1,2,3,4,5,6,7]
a=[]
for i in sub:
def res(i):(sub/12)*100 #this is the formula
a.append(res(i))
print(a)
formula:
(sub/12)*100
i am getting this error:
Traceback (most recent call last):
File "c:\Users\suh\Desktop\se proj 2\backend.py", line 62, in <module>
a.append(res(i))
File "c:\Users\suh\Desktop\se proj 2\backend.py", line 61, in res
def res(i):(sub/12)*100
TypeError: unsupported operand type(s) for /: 'list' and 'int'
CodePudding user response:
There are several things going on here:
First of all, don't define a function inside of a loop. You want to define the function that implements the logic of the formula separately and call it from within the loop.
You also need to use return
in the function in order to send the calculated value back to whoever called the formula
function.
Secondly, you want to go over each element in the sub
list, apply the formula on it and then append the result to a list.
In addition, it is a good idea to provide meaningful variable names (a
and res
are not meaningful).
Applying the above, you get this:
def formula(num):
return (num / 12) * 100 # this is the formula
sub = [1,2,3,4,5,6,7]
sub_after_formula = []
for num in sub:
sub_after_formula.append(formula(num))
print(sub_after_formula)
Output:
[8.333333333333332, 16.666666666666664, 25.0, 33.33333333333333, 41.66666666666667, 50.0, 58.333333333333336]
As @JonSG mentioned, it is recommended to use the list comprehension instead of the for
loop in cases like this:
sub_after_formula = [formula(x) for x in sub]
CodePudding user response:
For this small list, the list comprehension / map approach is great.
For a larger list, or if you plan to do more mathematical operations on the list, it might be worth looking into the numpy
library. This often results in a significant speed increase, and can simplify the code.
Once you convert the list to a numpy array, you can perform vectorised operations:
sub = [1,2,3,4,5,6,7]
sub_array = np.array(sub)
result = (sub_array/12) * 100
print(result)
Or we can use a function and pass the array directly:
def formula(num):
return (num / 12) * 100
sub_array = np.array(sub)
result = formula(sub_array)
print(result)
For a slight speed increase, you can use formula(np.fromiter(sub,dtype=np.int32))
from https://stackoverflow.com/a/59509701/9555388
CodePudding user response:
sub=[1,2,3,4,5,6,7]
a=[]
for i in sub:
res = (i/12)*100 #this is the formula
a.append(res)
print(a)
You shouldn't make a function in a for loop. In this example as per me no function is needed. You are getting the error actually because your formula is (sub/12)*100 while sub is a list. i is the item there not sub your formula should be (i/12)*100 You can't divide a list with 12., but an integer which is i here