Here is the code:
import random lines = int(input("Enter number of lines: ")) for j in range(lines): n = random.randint(0,50) mass = [[n] * lines for i in range(lines)] for iter in mass: print(' '.join([str(elem) for elem in iter])) Here is the code:
import random lines = int(input("Enter number of lines: ")) for j in range(lines): n = random.randint(0,50) mass = [[n] * lines for i in range(lines)] for iter in mass: print(' '.join([str(elem) for elem in iter])) In [10]: import random In [11]: def get_random_matrix(rows_count): ...: matrix = [[random.randint(0, 50) for _ in range(rows_count)] for _ in range(rows_count)] ...: return matrix Result:
In [12]: get_random_matrix(5) Out[12]: [[15, 23, 48, 48, 6], [44, 48, 0, 7, 23], [24, 15, 25, 11, 49], [49, 5, 40, 3, 22], [43, 0, 44, 47, 16]] I noticed that in this:
for iter in mass:
A piece of code you specified iter , I do not advise you to do so, since this is a reserved word in Python:
In [1]: iter Out[1]: <function iter> Try this:
mass = [[random.randint(0,50) for i in range(lines)] for j in range(lines)] Use primitive debugging (printing) - and everything will immediately become clear:
In [38]: lines = 3 In [39]: for j in range(lines): ...: n = random.randint(0,50) ...: mass = [[n] * lines for i in range(lines)] ...: print(mass) ...: [[30, 30, 30], [30, 30, 30], [30, 30, 30]] [[29, 29, 29], [29, 29, 29], [29, 29, 29]] [[45, 45, 45], [45, 45, 45], [45, 45, 45]] In [40]: print(mass) [[45, 45, 45], [45, 45, 45], [45, 45, 45]] If you have a practical, not an academic task, then you can use Numpy:
In [30]: import numpy as np In [31]: lines = 10 In [32]: mass = np.random.randint(50, size=(lines,lines)) In [33]: mass Out[33]: array([[26, 11, 45, 26, 1, 13, 24, 15, 23, 32], [38, 44, 6, 9, 40, 11, 41, 15, 25, 22], [47, 48, 12, 12, 4, 24, 41, 20, 29, 39], [39, 33, 16, 3, 23, 14, 49, 23, 37, 48], [27, 23, 47, 17, 29, 34, 24, 42, 33, 3], [ 1, 32, 43, 39, 37, 27, 42, 38, 33, 48], [49, 12, 15, 21, 30, 28, 9, 20, 24, 13], [ 3, 11, 21, 44, 14, 12, 2, 38, 10, 1], [12, 27, 26, 19, 23, 21, 39, 28, 26, 32], [36, 28, 20, 44, 3, 4, 7, 34, 7, 31]]) Source: https://ru.stackoverflow.com/questions/744513/
All Articles