1

以下のコードを実行すると、反復は0から始まります。行を1行目から開始するように変更したいのですが、どうすれば変更できますか?反復が始まる前にrownum=1と入力してみました。

コード:

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:

どんな助けでも大歓迎です。

4

4 に答える 4

8

変化する:

for rownum in range (rows):

に:

for rownum in range (1, rows+1):
于 2012-04-13T11:51:06.227 に答える
5

range()開始値を取ることもできます:range(1, rows+1)

詳細については、Pythonドキュメントを参照してください

于 2012-04-13T11:50:55.570 に答える
4

この行を変更します。

for rownum in range (rows):

の中へ:

for rownum in range (1, rows+1):
于 2012-04-13T11:51:28.077 に答える
1

変更するだけ

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

def routes(rows,current_row=1,start=1):
于 2012-04-13T11:51:46.250 に答える