S
S
sasha3002018-09-30 16:17:21
Python
sasha300, 2018-09-30 16:17:21

How to display a matrix in a classical form (not a linear list)?

Hello!
There is a script that displays the matrix as a linear list:

import random
z = 4
x = random.sample(range(50), z)
y = random.sample(range(50), z)
for i in x:
    for u in y:        
        print(i*u)

which will result in:
spoiler
14
259
343
42
68
1258
1666
204
74
1369
1813
222
84
1554
2058
252

Is it possible to place a code in a nested loop that will display the matrix in the classic form:
[1, 2, 3, 4]
[1, 2, 3, 4]
4 8 12 16
3 6 9 12
2 4 6 8
1 2 3 4

It's been over two days and nothing comes to mind.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2018-09-30
@sasha300

Two days - yes you are cool, my head hurts from a five-minute thought!

for i in x:
        print(*[i*u for u in y])

S
Sergey Gornostaev, 2018-09-30
@sergey-gornostaev

import random

z = 4
x = random.sample(range(50), z)
y = random.sample(range(50), z)

for i in x:
    for u in y:        
        print('{:4d}'.format(i*u), end=' ')
    print('')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question