Reputation: 911
I have done some writing like below
new_list = ["000","122","121","230"]
for item in new_list:
r = [np.matrix([[0.5,0.5],[0,1]]),
np.matrix([[0.5,0.25],[0,1]]),
np.matrix([[0.5,0.25],[0,1]]),
np.matrix([[0.5,0],[0,1]])]
(W0,W1,W2,W3) = r
for i in item:
i == 0
if item[i] == 0:
return W0
elif item[i] == 1:
return W1
elif item[i] == 2:
return W2
else:
return W3
i = i + 1
list_new = [np.matrix([1,0]) * new_list * np.matrix([0.5],[1])]
print(list_new)
I want to create a program for example when the input from the list is "122", it will multiply each element inside "122" as matrix W1*W2*W2. The final result should be like
np.matrix([1,0]) * new_list2 * np.matrix([0.5],[1])
The
new_list2
here should be all multiplication result from the new_list. Meaning
new_list2 = [W0*W0*W0,W1*W2*W2,...]
I run this code and keep getting a syntax error saying
"return" outside function
I want to ask did I missed something here or there is other function/way to make it done using python. I am using Python 3.5 Thank you for the answer.
Upvotes: 0
Views: 256
Reputation: 12273
Something like this?
import numpy as np
from functools import reduce
new_list = ["000", "122", "121", "230"]
matrices = [
np.matrix([[0.5,0.50],[0,1]]),
np.matrix([[0.5,0.25],[0,1]]),
np.matrix([[0.5,0.25],[0,1]]),
np.matrix([[0.5,0.00],[0,1]])
]
def multiply(s):
mt_seq = (matrices[i] for i in map(int, item))
return reduce(np.multiply, mt_seq) # or reversed(mt_seq)
for item in new_list:
print(multiply(item))
You can just convert each digit in the string with int(digit)
, e.g. int('2')
, and do it for every element of the string with map(int, '01234')
.
Then, it's just a matter of taking those matrices and multiplying them. (Sorry, I am not familiar with np.multiply
and np.matrix
and maybe you need to reverse the order of multplication)
reduce(fun, seq)
applies fun to seq, like this: fun(fun(fun(seq[0], seq[1]), seq[2]), ...)
Upvotes: 1
Reputation: 77912
As the error message says, you are using "return" outside a function, which just doesn't make sense since "return" means "exit the function now and pass this value (or None
if you don't specify a value) to the caller". If you're not inside function there is no caller to returns to...
Upvotes: 1