2012-04-13 50 views
1

當我運行下面的代碼時,迭代從0開始。我想將行從第1行開始更改。我該如何更改它?我在迭代開始之前嘗試輸入rownum = 1。Iterartion以0開始

代碼:

def triangle(rows): 
    for rownum in range (rows): 
     PrintingList = list() 
     print ("Row no. %i" % rownum) 
     for iteration in range (rownum): 
      newValue = input("Please enter the %d number:" %iteration) 
      PrintingList.append(int(newValue)) 
      print() 
def routes(rows,current_row=0,start=0): 
      for i,num in enumerate(rows[current_row]): #gets the index and number of each number in the row 
       if abs(i-start) > 1: # Checks if it is within 1 number radius, if not it skips this one. Use if not (0 <= (i-start) < 2) to check in pyramid 
        continue 
       if current_row == len(rows) - 1: # We are iterating through the last row so simply yield the number as it has no children 
        yield [num] 
       else: 
        for child in routes(rows,current_row+1,i): #This is not the last row so get all children of this number and yield them 
         yield [num] + child 

numOfTries = input("Please enter the number of tries:") 
Tries = int(numOfTries) 
for count in range(Tries): 
    numstr= input("Please enter the height:") 
    rows = int(numstr) 
    triangle(rows) 
    routes(triangle) 
    max(routes(triangle),key=sum) 

輸出:

Please enter the number of tries:2 
Please enter the height:4 
Row no. 0 
Row no. 1 
Please enter the 0 number: 

任何幫助表示讚賞。

+1

的Python具有的所有功能的描述有一個好的文檔:['range'](HTTP ://docs.python.org/library/functions.html#range),['enumerate'](http://docs.python.org/library/functions的.html#枚舉)。你應該學會如何使用它,這是非常寶貴的。 – 2012-04-13 11:52:47

+0

感謝您的回覆。愛提供的幫助..... – lakesh 2012-04-13 11:55:09

+0

請注意,CamelCase名稱通常是Python中的類名,而不是常規變量。 – phant0m 2012-04-13 12:35:41

回答

8

變化:

for rownum in range (rows): 

到:

for rownum in range (1, rows+1): 
5

range()也可以採取一個初始值:range(1, rows+1)

欲瞭解更多信息,請參閱Python Docs

+0

請注意,這引入了一個錯誤的錯誤。 – NPE 2012-04-13 11:53:08

+0

@aix true,已修復。 – mensi 2012-04-13 11:54:08

4

改變這一行:

for rownum in range (rows): 

分爲:

for rownum in range (1, rows+1): 
1

只要改變

def routes(rows,current_row=0,start=0): 

def routes(rows,current_row=1,start=1):