In: Computer Science
This is a python question.
Write a function mult_table(n) that consumes a natural number n and returns the n+1 by n+1 multiplication table (where each entry in the inner list is equal to the product of which list it is and the inner list position number, or in other words, the product of the row and column numbers). Use accumulative recursion.
def mult_table(n)
'''
Returns the n+1 by n+1 multiplication table
mult_table: Nat => (listof (listof Nat))
Examples:
mult_table(0) => [[0]]
mult_table(1) => [[0, 0],
[0, 1]]
mult_table(2) => [[0, 0, 0],
[0, 1, 2],
[0, 2, 4]]
mult_table(5) => [[0, 0, 0, 0, 0, 0],
[0, 1, 2, 3, 4, 5],
[0, 2, 4, 6, 8, 10],
[0, 3, 6, 9, 12, 15],
[0, 4, 8, 12, 16, 20],
[0, 5, 10, 15, 20, 25]]
'''
No loops! Only accumulative recursion can be used!
1).ANSWER:
GIVEN BELOW:
#code
# required method
def mult_table(n):
# we are using abstract method map with lambda to construct an n+1
x n+1 list
# containing the required multiplication table.
# range(n+1) will return an iterable that contains value between 0
and n
# list(map(lambda col: row * col, range(n + 1))) will go through
each value
# between 0 and n for col, multiply the value with row and returns
a list
# list(map(lambda row: list(map(lambda col: row * col, range(n +
1))),range(n+1))) will
# simply loop the above process for row value between 0 and n,
adding each returned list
# into another list and returns it
r = list(map(lambda row: list(map(lambda col: row * col, range(n +
1))), range(n + 1)))
return r
print(mult_table(5))
'''
consider below example, if you want to understand how above
function works
suppose n=5 and row=3 (means we are currently processing row
3)
the below statement will print [0, 3, 6, 9, 12, 15]
print(list(map(lambda col: row * col, range(n + 1))))
explanation:
range(n + 1) returns [0,1,2,3,4,5]
the map function loops through each item in above list, multiply
value with 3 (current row)
so [0, 1, 2, 3, 4, 5] becomes [0, 3, 6, 9, 12, 15], this list is
returned
similarly, this process is repeated for rows between 0 and n,
and the returned list from each
inner call to list(map(lambda col: row * col, range(n + 1))) is
stored in a list of lists
'''
#output
[[0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5], [0, 2, 4, 6, 8, 10], [0, 3, 6, 9, 12, 15], [0, 4, 8, 12, 16, 20], [0, 5, 10, 15, 20, 25]]