blackened
blackened

Reputation: 903

Getting Rid of Needless Arguments

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))

(I have a feeling that this is a stupid question, and possibly asked already, but I do not know how to search for it.)

In the above code calculateSums function will always receive the same arguments, thus it seems silly to pass them in. Yet I could not figure out how to manage them inside the function. What am I supposed to do?

Upvotes: 1

Views: 35

Answers (1)

Alex
Alex

Reputation: 21766

You could use default parameters:

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

You can then make the initial call without parameters:

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

However, be careful when using expressions in default arguments. These are calculated when the function is defined, not when it’s called.

Upvotes: 1

Related Questions