I am trying to pass all the arrays such as molecularWeight(concentration,time) `
concentration_time = np.array([[0,83],
[0.04,89],
[0.06,95],
[0.08,104],
[0.1,114],
[0.12,126],
[0.14,139],
[0.16,155],
[0.20,191]])
concentration = [item[0] for item in concentration_time]
time = [item[1] for item in concentration_time]
t0 = 83
def molecularWeight(c,t):
answer = ((t/t0)-1)/c
return answer
molecularWeight(concentration,time)
I was expecting to get an output with 9 different outputs. I want to pass all pairs for c and t and get an output for each.
I get the desired output when I manually pass the values:molecularWeight(0.04,89.0)
but not when I try to pass all of them using the previously defined variables: molecularWeight(concentration,time)
ERROR:
TypeError: unsupported operand type(s) for /: 'list' and 'int'
CodePudding user response:
Lists in python do not support addition/subtraction/other mathematical operations.
You need to either use numpy
, or explicitly do the operations within a list-comprehension (or loop) over the zipped
element pairs...
For instance:
import numpy as np
def molecularWeight(c,t):
c = np.array(c)
t = np.array(t)
answer = ((t/t0)-1)/c
return answer
molecularWeight(concentration,time)
or conversely:
def molecularWeight(c,t):
try:
answer = ((t/t0)-1)/c
except TypeError:
answer = [((t_/t0)-1)/c_ for c_, t_ in zip(c, t)]
return answer
molecularWeight(concentration,time)
Note that you started off with a numpy
array, so you could just stick to that from the start, leave the function as you defined it, but make sure to pass in numpy-arrays and not lists:
concentration = concentration_time[:, 0]
time = concentration_time[:, 1]
CodePudding user response:
add safety for your division (1e-9) here for example to avoid div to zero
concentration ,time = concentration_time[:,0], concentration_time[:,1]
t0 = 83
def molecularWeight(c,t):
return ((t / t0) - 1) / (c 1e-9)
molecularWeight(concentration,time)
CodePudding user response:
This is probably what you want, if I'm understanding correctly.
You are correctly giving the list to the function as an input, but not iterating over it correctly.
def molecularWeight(inputs):
answers = []
for c, t in inputs:
answer = ((t/t0)-1)/c
answers.append(answer)
return answers