2015-11-06 30 views
1
import random 


def makeTable(f, v): 
    f = random.randint(1, 7) 
    v = random.randint(f, 10) 
    table = [[0 for x in range(v)] for y in range(f)] 
    for i in range(f): 
     for j in range(v): 
      table[i][j] = random.randint(1, 100) 
    return table 


def printTable(table): 
    # print the table (helpful for visualizing) 
    for i in range(len(table)): 
     print("\t".join(str(a) for a in table[i])) 


def calculateSums(startRow, startColumn, initialSum): 
    if startRow == f - 1: 
     # if the last row is reached add each of the coming values 
     # to the variable initialSum and append to the list totalSums. 
     for k in range(startColumn, v): 
      totalSums.append(initialSum + table[f - 1][k]) 
    else: 
     while startColumn <= (v - f + startRow): 
      # the constraint (v-f+startRow) determines the limit 
      # how far each row can go to the right. 
      # e.g. in a 3*5 table the limit for the first row is the third column, 
      # the limit for the 2nd row is the fourth column, etc. 
      initialSum += table[startRow][startColumn] 
      calculateSums(startRow + 1, startColumn + 1, initialSum) 
      initialSum -= table[startRow][startColumn] 
      startColumn += 1 

    return max(totalSums) 


f = random.randint(1, 7) 
v = random.randint(f, 10) 
# generate the number of flowers, f, and number of vases, v. 

table = makeTable(f, v) 
print('Number of flowers: ', f) 
print('Number of vases: ', v) 
printTable(table) 
totalSums = [] 

print('Maximum sum is: ', calculateSums(0, 0, 0)) 

(我有一種感覺,這是一個愚蠢的問題,可能問了,但我不知道如何尋找它。)擺脫不用參數

在上面的代碼calculateSums功能總是會收到相同的論點,所以通過它們似乎很愚蠢。但是我不知道如何在函數內部管理它們。我應該做些什麼?

+0

此代碼是否按預期工作?看起來'calculateTable'中的'f'和'calculateSums'中的'f'可能沒有全局作用域。你嘗試過'pylint'嗎? – lit

+0

@Liturgist代碼正常工作。 – blackened

回答

1

你可以使用默認參數:

def calculateSums(startRow=0, startColumn=0, initialSum=0): 

然後,您可以進行初始呼叫不帶參數:

print('Maximum sum is: ', calculateSums()) 

然而,在默認參數使用表達式時要小心。這些是在函數被定義時計算的,而不是被調用的。

+0

爲什麼'def calculateSums(startRow = 0,startColumn = 0,initialSum = 0):'和擺脫'if語句'不工作? – blackened

+0

你可以在這種情況下,但要小心。在Python中,默認參數中的表達式是在函數被定義時計算的,而不是在被調用時計算的 – Jaco