2016-04-07 18 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) 
相關問題