高效编码带有变量名称的循环

时间:2012-05-06 03:04:14

标签: python performance loops

我有一些我定义为函数的公式。

然后我使用特定参数'命名'它们,因为我需要在更进一步的公式中使用输出,这使得它更容易和更整洁。

我现在需要循环定义的函数来给出一年中每个月的输出,当我将函数的名称放入while循环时,它只给了我一个答案12次,但是当我将完整的函数放入它运行的循环中。

有没有办法可以通过使用它的名称来循环该函数,因为随着我的公式的进展,它们变得越来越复杂,代码变得越来越困惑。

def growPOP(p, T, r, K):
    #formula to calculate the new population at the end of a month.
    #p = initial population, T = total initial population
    #r = growth rate per time, K = carrying capacity
    GrPp = p + ((p * r)*((K - T) / K))
    return(GrPp)

def rt(a, b, t):
    #formula to calculate growth rate for brown fish
    #a & b are constants given, t = the month number
    rt = a + (b*sin(((2*pi)*t)/12))
    return rt

ca = 0.052
cb = 0.132   
brownPOP = 19000
goldPOP = 4400
totalPOP = brownPOP + goldPOP
carryK = 104800
redcarryK = 0.998
newcarryK = (carryK*redcarryK) + (ep/10) #ep is an input figure - for now it's 0.
month = 1
brownGrowth = growPOP(brownPOP, totalPOP, rt(ca, cb, month), carryK)

while month <= 2:
    print "Month ", month
    print "Grown brown fish: ", growPOP(brownPOP, totalPOP, rt(ca, cb, month), carryK)
    brownPOP = endbrownPOP
    goldPOP = endgoldPOP
    totalPOP = endtotalPOP
    carryK = newcarryK
    month = month + 1

所以在上面的循环中它给出了我想要的输出,但是我真的希望循环说“打印”成长的棕色鱼:“,brownGrowth”并且仍然有效。

还有其他公式可以将brownPOP转换为endbrownPOP,但是有很多并且它们有效,所以我认为不需要输入它们来使事情变得复杂。

3 个答案:

答案 0 :(得分:1)

如果我正确地阅读了您,您希望brownGrowth存储函数调用growPop()的结果,而是成为那个函数调用。因此,您要做的是将brownGrowth 定义为函数。

brownGrowth = lambda: growPOP(brownPOP, totalPOP, rt(ca, cb, month), carryK)

然后在你的循环中,调用该函数:

print "Grown brown fish: ", brownGrowth()

然而,你现在拥有它的方式确实没有任何问题,我认为你想改变它的方式并不清楚 - 事实上,它隐藏了无争议函数背后的数字。此外,没有什么比这更有效了:它的更少效率,因为配方中有一层额外的函数调用。

答案 1 :(得分:0)

我想你忘了在每次循环迭代中重新计算brownGrowth?

brownGrowth = growPOP(brownPOP, totalPOP, rt(ca, cb, month), carryK) 
while month <= 2: 
    print "Month ", month 
    print "Grown brown fish: ", brownGrowth
    brownPOP = endbrownPOP  
    goldPOP = endgoldPOP  
    totalPOP = endtotalPOP  
    carryK = newcarryK  
    month = month + 1  

brownGrowth = formula行移至内部,同时循环:

while month <= 2: 
    brownGrowth = growPOP(brownPOP, totalPOP, rt(ca, cb, month), carryK) 
    print "Month ", month 
    print "Grown brown fish: ", brownGrowth
    brownPOP = endbrownPOP 
    goldPOP = endgoldPOP 
    totalPOP = endtotalPOP 
    carryK = newcarryK 
    month = month + 1 

答案 2 :(得分:0)

除了使用lambda:

brownGrowth = lambda: growPOP(brownPOP, totalPOP, rt(ca, cb, month), carryK)

你也可以使用functools中的partial

from functools import partial
brownGrowth = partial(growPOP, brownPOP, totalPOP, rt(ca, cb, month), carryK)

然后称之为:

print "Grown brown fish: ", brownGrowth()

但是,再一次,它完全没必要,只需将函数调用放在循环中,它的代码就少了。