Python - how to write this in vector form [closed]
def compute(c, r):
s = 0;
l = len(c);
for i in range(l):
s = s + c[i]*f(r[i]);
return s
I don't know what you mean by vector form (unless you are using numpy?), but I would write your function like this:
def compute(c, r):
return sum(x*f(y) for x,y in zip(c,r))
If you are using numpy you can use whole-array expressions instead of generator expressions, but in that case c
and r
must be numpy arrays:
def compute(c, r):
return (c*f(r)).sum()
精彩评论