2012-06-18 19 views
0

我該如何解決這個問題?在python中總結連續的第三個數字

程序應該包含函數sumTri(cutOff)的定義。該函數將Tri編號添加到總和中。

三個數字是每三個數字:1, 4, 7, 10, ....該函數將連續三個數字1, 4, 7, ...添加到總和中,只要Tri數小於cutOff。該函數返回這些數字的總和。

+8

家庭作業,我假設? (如果是這樣,這沒關係;僅僅意味着我們應該提示而不是解決方案。)到目前爲止你嘗試過了什麼? – DSM

回答

5

很簡單:

def sumTri(cutOff): 
    return sum(range(1,cutOff,3)) 

或者,當你需要它的低級:

def sumTri(cutOff): 
    sum = 0 
    tri = 1 
    while tri < cutOff: 
    sum += tri 
    tri += 3 
    return sum 

我會試着解釋這兩個soultions一點點。

在第一種情況下,您使用Python的兩個「高級」函數,它們都可以幫助您:sumrangerange(a,b,c)函數生成一個從ab之間的數字列表,其間的步驟爲c。例如: -

In [1]: range(1,10,3) 
Out[1]: [1, 4, 7] 

In [2]: range(1,22,3) 
Out[2]: [1, 4, 7, 10, 13, 16, 19] 

你必須在這裏指出,range生成數字,直到在列表中的數小於b,而不是更少,或相等。正是你的任務需要你。

而且sum顯然計算並返回,它有作爲它的參數列表中的數字的總和:

In [3]: sum([1]) 
Out[3]: 1 

In [4]: sum([1,2]) 
Out[4]: 3 

In [5]: sum([1,2,3]) 
Out[5]: 6 

現在,你只需要到這兩個功能結合起來:

return sum(range(1,cutOff,3)) 

的第二個解決方案更「低級」和「算法」。你不用在這裏使用特殊的python函數,自己做一切。

您使用兩個變量來計算的總和:

  • sum - 在您存儲和
  • tri變量 - 與你一步
  • 增加步數的當前值的變量

當你寫類似:

a = a + 5 

這意味着:「現在我想要a等於a之前加5」或「增加a 5」。你可以寫得更短:

a += 5 

這兩種形式是等價的。

但你不需要簡單地添加一些東西。你需要做很多次,直到發生事情。在Python做使用while

while someting-is-true: 
    do-something 

每次while檢查something-is-true狀態,當它是真的,它使那些while下命令(縮進)即do-something

現在你知道了一切必要寫的解決方案:

def sumTri(cutOff): 
    sum = 0      # we start the sum from 0 
    tri = 1      # and the first number to add is 1 
    while tri < cutOff:   # next number to add < cutOff? 
    sum += tri     # than add it to sum 
    tri += 3     # and increase the number by 3 
    return sum     # now you have the result, return it 

這是做這項工作的功能。現在你可以使用該功能。 你如何做到這一點?

def sumTri(cutOff): 
    ... 

# anywhere in you program: 
# presuming a is the cutOff 
print sumTri(a) 

當你要運行的功能,並使用它的結果你只寫function_name(args)

+2

大概的家庭作業 - 也許解釋你的工作? – andrewdotnich

+1

[如何提問和回答作業問題](http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions) – juliomalegria

+0

@andrew,julio:謝謝你的建議,添加說明 –

4

該序列與triangular numbers

這裏是一個爲O​​(1)

def sumTri(cutoff): 
    n = (cutoff+1)//3 
    return (3*n-1)*n//2