2016-04-07 17 views
0

所以我的代码使用Python和的一个系列

def formula(n): 
    while(n < 11): 
     answera = 15/(-4)** n 
     print(answera) 
     n = n + 1 

formula(1) 

我怎样才能在居高临下的顺序添加输出?

例如,

first_output = (the output of n = 1) 

second_output = (the output of n = 1) + (the output of n = 2) 

third_output = (the output of n = 1) + (the output of n = 2) + (the output of n = 3) 

等..

+0

n输出=输出当n +(N-1)个输出 –

+0

你关心中间输出吗?也就是说,如果你看到“公式(1)”和“公式(2)”是什么样子,你是否在意?并且要清楚:你想采用'公式'并将其应用于输入列表,如1,2,3 ...,对吗? – Makoto

+0

你的功能不清楚。对于'n = 1',结果应该是10次'15 /( - 4)** n' 10次不同'n'值的总和吗?或'公式(n)'应该返回'15 /( - 4)** n'? – ozgur

回答

3

您需要在while循环之外定义变量answera,以便其shope应存在于循环外部,以便在返回值时可以返回完全更新的值。像这样的东西。

def formula(n): 
    answera = 0 
    while(n < 11): 
     answera += 15/(-4)** n 
     print(answera) 
     n = n + 1 
    print(answera) 

formula(1) 

现在它应该给你正确的结果。

1
def formula(n): 
    while(n < 11): 
     answera += 15/(-4)** n 
     print(answera) 
     n = n + 1 

的想法是,你将需要accumlate的15/(-4)**n值中的一个变量。(这里的answera )并保持打印出来。

我希望这能回答你的问题。

0

你的问题存在一些不明确之处;你想要'answera'的总和还是'公式'的总和?

如果“answera”,那么你可以将“打印”与“产量”,并呼吁“和”:

def formula(n): 
    while(n < 11): 
     answera += 15/(-4)** n 
     yield answera 
     n = n + 1 

sum(formula(2)) 

这使得“公式”一个generator,而“和”会遍历该发电机直到它筋疲力尽。

如果你想多“公式”的总和来电,然后按照KISS原则,并与其他功能的包装你的功能:

# assuming that 'formula' is a generator like above 

def mega_formula(iterations): 
    total = [] 
    for i in range(1, iterations + 1): # b/c range indexs from zero 
     total.append(sum(formula(i)) 
    return sum(total) 
相关问题