【发布时间】:2012-05-06 03:04:14
【问题描述】:
我有一些公式已定义为函数。
然后我使用特定参数为它们“命名”,因为我需要在进一步的公式中使用输出,这使它更容易和更整洁。
我现在需要循环定义的函数以提供一年中每个月的输出,当我将函数的名称放入 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
所以在上面的循环中,它给出了我想要的输出,但我真的希望循环说“打印”Grown brown fish:“,brownGrowth”并且仍然可以工作。
还有其他公式可以将 brownPOP 转换为 endbrownPOP,但有很多公式,它们都有效,所以我认为不需要输入它们会使事情复杂化。
【问题讨论】:
标签: python performance loops