[英]How can I combine two almost same functions but return different output efficiently
I have two functions, which are almost same, in a main function.我在主 function 中有两个几乎相同的功能。 For a simplified example,
举一个简化的例子,
def func1(a):
for i in range(999):
a += np.exp(-i) # some massive calculation
return a
def func2(a):
b = 0
for i in range(999):
a += np.exp(-i) # same massive calculation
b += np.exp(-(a+b)) # additional massive calculation
return a, b
def main():
a = 1
for _ in range(9999):
a = func1(a)
print(a)
a = 0
c = 0
for _ in range(9999):
a, b = func2(a)
c +=b
print(a, c)
I know I could have combined func1
and func2
as我知道我可以将
func1
和func2
组合为
def func3(a, return_b):
b = 0
for i in range(999):
a += np.exp(-i)
if return_b: # add if statement
b += np.exp(-(a+b))
return a,b
and the main function becomes和主要的 function 变成
def main():
a = 1
for _ in range(9999):
a,_ = func3(a, False)
print(a)
a = 0
c = 0
for _ in range(9999):
a, b = func3(a, True)
c +=b
print(a, c)
But I think it's really expensive to add if statement in a large number of loops.但是我认为在大量循环中添加 if 语句确实很昂贵。 And I would rather repeat
func1
in func2
and leave both functions in the code.我宁愿在
func2
中重复func1
并将这两个函数留在代码中。 I wonder what the best way is to combine func1
and func2
together by considering the running time and code re-use efficiency.考虑到运行时间和代码重用效率,我想知道将
func1
和func2
结合在一起的最佳方法是什么。
This code below is less expensive than if inside for loop and as you wanted it still is in one function.下面的这段代码比 if inside for 循环更便宜,而且你想要它仍然在一个 function 中。
def func3(a, return_b):
b = 0
#checks only once
if return_b:
for i in range(999):
a += np.exp(-i)
b += np.exp(-(a+b))
else:
for i in range(999):
a += np.exp(-i)
return a,b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.