My objective is to show on the screen a row " x " and a column " y " entered by keyboard, of a matrix of any order, which contains randomly generated numbers, the idea is that if it is for example a 3x3 matrix, and to enter by keyboard x=3 and also y=3, show what corresponds (row 2 and column 2 of the matrix respectively, since the matrix starts from 0 to 2 because it is 3x3 , row 1 is row 0, row 2 is row 1 and row 2 is row 3, the same with the columns of the matrix), all this verification is already resolved, the problem is to correctly display the requested row and column, that is, if we have, for example, the The next generated array should have the following form:
1 2 3
4 5 6
7 8 9
and if I request by keyboard, row 1, column 3 (ie row 0 and column 2):
1 2 3
6
9
My code is the following:
import random
import os
def Mostrar(): #Todo este bloque funciona
x=fila+1;y=columna+1 #Si queremos ver la fila 0 y columna 0, se debe ingresar fila 1 y columna 1
while (x-1)<0 or x>=(fila+1) or (y-1)<0 or y>=(columna+1):
x=int(input("X: ")) #se ingresa la fila a visualizar
y=int(input("Y: ")) #se ingresa la columna a visualizar
if (x-1)<0 or x>=(fila+1) or (y-1)<0 or y>=(columna+1):
print("fila y columna invalida")
else: #Pero la matriz no se está mostrando adecuadamente
for i in range(fila):
for j in range(columna):
if (x-1)==i or (y-1)==j:
print(matriz[i][j],"\t", end=" ")
else:
print("\t")
print()
fila=int(input("Fila: "))
columna=int(input("columna: "))
matriz = [ [ None for y in range( columna ) ] for x in range( fila ) ]
for i in range(fila):
for j in range(columna):
matriz[i][j]=random.randint(1,200)
Mostrar()
os.system("pause")
You just need this small change in your printing routine:
It is simply a) printing a value if row or column is the desired one, or b) printing whitespace to keep everything aligned.
The printing format
%4d
guarantees you to occupy four positions by value. If there is no value, then four spaces are printed in theelse:
Produces:
and another test: