我想應用一個函數的numpy數組的所有行,它的工作原理如果行中的列表具有相同的大小,但失敗時,只要有一個不同的大小。沿軸numpy應用與不同大小的陣列
的功能不OK
dat=np.array([['4','5','*','6','+','3','/'],['4','4','*','6','*'],['4','5','*','6','+'],['4','5','*','6','+']])
lout=np.apply_along_axis(parseRPN,0,dat)
print(dat)
print(lout)
OK
dat=np.array([['4','5','*','6','+'],['4','4','*','6','*'],['4','5','*','6','+'],['4','5','*','6','+']])
lout=np.apply_along_axis(parseRPN,0,dat)
print(dat)
print(lout)
我是否使用R應用
from math import *
import operator
def parseRPN(expression,roundtointeger=False):
"""Parses and calculates the result of a RPN expression
takes a list in the form of ['2','2','*']
returns 4
"""""
def safe_divide(darg1, darg2):
ERROR_VALUE = 1.
# ORIGINAL ___ Here we can penalize asymptotes with the var PENALIZE_ASYMPITOTES
try:
return darg1/darg2
except ZeroDivisionError:
return ERROR_VALUE
function_twoargs = {'*': operator.mul, '/': safe_divide, '+': operator.add, '-': operator.sub}
function_onearg = {'sin': sin, 'cos': cos}
stack = []
for val in expression:
result = None
if val in function_twoargs:
arg2 = stack.pop()
arg1 = stack.pop()
result = function_twoargs[val](arg1, arg2)
elif val in function_onearg:
arg = stack.pop()
result = function_onearg[val](arg)
else:
result = float(val)
stack.append(result)
if roundtointeger == True:
result=stack.pop()
result=round(result)
else:
result=stack.pop()
return result
該工作的ight工具?這裏的想法是將計算向量化爲一系列列表。
感謝
'parseRPN'是什麼樣的? – Kyle
如果我在第一個數組上應用另一個函數('def test(a):return a;')而不是'parseRPN',它對我有用。問題可能在'parseRPN'中? –
只是一個說明:你不會得到任何性能收益。 'apply_along_axis'不是矢量化的,非矩形數組不允許矢量化 –