0

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
ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52
Bilow
  • 25
  • 1
  • 5

2 Answers2

0

Try this:

mm = []
ll = []

def mul(d):
    for i in range(1,d+1):
        ll = []
        for l in range(1,d+1):
#             print(i*l),
            ll.append((i*l)) 
        mm.append(ll)

mul(5)

for x in mm:
   print(x)

[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]
Merlin
  • 24,552
  • 41
  • 131
  • 206
  • I really need them to be printed in the shape of a dxd matrix the solutions are already fine in my function. – Bilow Jun 05 '16 at 11:04
  • Well, then edit your question with the dxd output you want. – Merlin Jun 05 '16 at 11:05
  • @Merlin That's something quite interesting! However, this only works for Python 2. In Python 3, it will just print it in a straight line. – Moon Cheesez Jun 05 '16 at 11:09
  • @MoonCheesez okay didnt know that. Maybe i should edit that i need it for python 3.x :D – Bilow Jun 05 '16 at 11:11
0

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.

EDIT

The above example will work for both Python 3 and Python 2. However, for Python 3 (as @richard has put in the comments), you can use:

def mul(d):
    for i in range(1, d+1):
        for l in range(1, d+1):
            print(i*l, end=" ")
        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
Community
  • 1
  • 1
Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38