2014-11-03 58 views
0

這是question 14 in project euler,但我在創建循環時遇到了問題......但是拉出/計算了我從循環創建的數字。我目前正在通過PE學習如何使用python。Project Euler(Python)#14 - 從「if」循環中提取數據

這裏我我的代碼以註釋:

import time # gets the time functionality 

start = time.time() # starts the timer 

def seq(x, count = 1): # This is a function, with the parameter of x and counting 

    seq = [x] # a data frame for the Collatz Sequence with x being placed in there 

    if x < 1: 

     return count 

    while x > 1: 

     count += 1 

     if x % 2 == 0: # determines if the number is even or not 

      x = x/2 

     else: 
      x = (3 * x) + 1 

    seq.append(count) # adds all the answers generated to the seq data fram 

max = [0,0] # define a new placeholder to "hold" the numbers you find, first[0] is number, and second[1] is length 

for i in range(10): 

    c = seq(i) 

    if c > max[0]: # if the length is > 0 put the new length here (below) 

     max[0] = c 
     max[1] = i # once you know the length is greater, you can put the value in the box as well 

elapsed = (time.time() - start) 

print "The program found the number %s has the longest length at %s, in %s seconds" % (max[1], max[0], elapsed) 

例如,當我把:

seq(10) 

我的輸出是:

[1, 1] 
[2, 2] 
[3, 8] 
[4, 3] 
[5, 6] 
[6, 9] 
[7, 17] 
[8, 4] 
[9, 20] 

隨着第一列是作爲數評估,其次是櫃檯。

然而,當我想提取使用max最大計數器(第二列)= [0,0]的數據幀,我不斷收到此錯誤:

The program found the number 0 has the longest length at 1, in 0.00015115737915 seconds 

但數字不能爲0和1,因爲輸出(上面)對於計數器的最大值爲20 ...所以文本輸出應該是9和20.

我可能不理解不同類型的數據,所以任何幫助表示讚賞。

回答

1

seq函數應該總是返回一個值,但現在它只有當x < 1.將return語句在年底返回的東西,太:

seq.append(count) # adds all the answers generated to the seq data fram 
return count 
+0

那麼,爲什麼「返回計」讓我代碼工作,但「打印計數」不? – Chef1075 2014-11-03 20:45:26

+1

因爲'print'和'return'做了完全不同的事情。沒有'return',當'c = seq(i)'執行時,'c'將被賦予'None'值,因此'如果c> max [0]'永遠不會成立。 – Kevin 2014-11-03 20:50:56