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 :(得分:1)
您可以使用默认参数:
def calculateSums(startRow=0, startColumn=0, initialSum=0):
然后您可以不带参数进行初始调用:
print('Maximum sum is: ', calculateSums())
但是,在默认参数中使用表达式时要小心。这些是在定义函数时计算的,而不是在调用函数时计算的。