Bilow Bilow - 6 months ago 8
Python Question

Printing all solutions in the shape of a matrix using \n\

This function returns all possible multiplication from 1 to d. I want to print the solution in the shape of a d×d matrix.

def example(d):
for i in range(1,d+1):
for l in range(1,d+1):
print(i*l)


For
d = 5
, the expected output should look like:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Answer

You could add the values in your second for loop to a list, join the list, and finally print it.

def mul(d):
    for i in range(1, d+1):
        list_to_print = []
        for l in range(1, d+1):
            list_to_print.append(str(l*i))
        print(" ".join(list_to_print))

>>> mul(5)
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

If you want it to be printed in aligned rows and columns, have a read at Pretty print 2D Python list.

Comments