python program for printing boundary elements of matrix - python

My code :
R = int(input("Enter the Size of Square Matrix : "))
matrix = []
print("\nEnter the entries row-wise : ")
for i in range(R):
a = []
for j in range(R):
a.append(int(input()))
matrix.append(a)
print("\nMatrix : \n")
for i in range(R):
for j in range(R):
print(matrix[i][j], end=" ")
print()
print("\n")
print("\nBoundary Matrix\n")
for i in range(R):
for j in range(R):
if (i == 0):
print(matrix[i][j])
elif (i == R - 1):
print(matrix[i][j])
elif (j == 0):
print(matrix[i][j])
elif (j == R - 1):
print(matrix[i][j])
else:
print(" "),
print()
output :
Boundary
Matrix
1
2
3
4
6
7
8
9
I'm not able to print the boundary elements in form of a matrix. the output is in form of a straight line.
Please help me to do so.
Note: I have tried changing the position of print() but that didn't help much.

print("\nBoundary Matrix\n")
for i in range(R):
print(
"{}{}{}".format(
"\t".join(map(str, matrix[i])) if i in (0, R - 1) else matrix[i][0],
"" if i in (0, R - 1) else (" \t" * (R - 1)),
"" if i in (0, R - 1) else matrix[i][R - 1],
)
)
Matrix :
1 2 3 4
5 6 7 8
9 10 11 12
13 1 4 15
Boundary Matrix
1 2 3 4
5 8
9 12
13 1 4 15

Related

Cant create a Sudoku level with python

I'm making a Sudoku that runs in terminal with python, and I can't assign numbers to fill up the board with numbers. Here is my code with all functions and main program. I think the error is in the checker for the number.
def createBoard ():
rows = 9
columns = 9
matrix = []
for r in range(rows):
matrix.append([]) # agregar lista
for c in range(columns):
matrix[r].append("")
return matrix
def printBoard (board):
for i in range (len(board)):
print (board[i])
def defineSubMatrix (row, column):
subMatrix = -1
if row >= 0 and row <= 2:
if column >= 0 and column <= 2:
subMatrix = 0
if column >= 3 and column <= 5:
subMatrix = 1
if column >= 6 and column <= 8:
subMatrix = 2
if row >= 3 and row <= 5:
if column >= 0 and column <= 2:
subMatrix = 3
if column >= 3 and column <= 5:
subMatrix = 4
if column >= 6 and column <= 8:
subMatrix = 5
if row >= 3 and row <= 5:
if column >= 0 and column <= 2:
subMatrix = 6
if column >= 3 and column <= 5:
subMatrix = 7
if column >= 6 and column <= 8:
subMatrix = 8
return subMatrix
def createLevel (board):
for i in range (0, 8):
for j in range (0, 8):
num = random.randint (1, 9)
check = checker(board, num, i, j)
while check == False:
if check == False:
num = random.randint (1, 9)
check = checker(board, num, i, j)
board[i][j] = num
board[i][j] = num
return board
def checker (board, num, posX, posY):
### ok = True cuando check == 0
ok = False
checkT = 0
checkR = 0
checkC = 0
checkSM = 0
###Check row right
i = posX
while i + 1 <= 8:
if board[i][posY] == num:
checkR += 1
i = i + 1
###Check row left
i = posX
while i - 1 >= 0:
if board[i][posY] == num:
checkR += 1
i = i - 1
###Check column down
j = posY
while j + 1 <= 8:
if board[posX][j] == num:
checkC += 1
j = j + 1
###Check column up
j = posY
while j - 1 >= 0:
if board[posX][j] == num:
checkC += 1
j = j - 1
###Check Submatrix
subMatrix = defineSubMatrix(posX, posY)
if subMatrix == 0:
for i in range (0, 2):
for j in range (0, 2):
if board[i][j] == num:
checkSM += 1
if subMatrix == 1:
for i in range (3, 5):
for j in range (0, 2):
if board[i][j] == num:
checkSM += 1
if subMatrix == 2:
for i in range (6, 8):
for j in range (0, 2):
if board[i][j] == num:
checkSM += 1
if subMatrix == 3:
for i in range (0, 2):
for j in range (3, 5):
if board[i][j] == num:
checkSM += 1
if subMatrix == 4:
for i in range (3, 5):
for j in range (3, 5):
if board[i][j] == num:
checkSM += 1
if subMatrix == 5:
for i in range (6, 8):
for j in range (3, 5):
if board[i][j] == num:
checkSM += 1
if subMatrix == 6:
for i in range (0, 2):
for j in range (6, 8):
if board[i][j] == num:
checkSM += 1
if subMatrix == 7:
for i in range (3, 5):
for j in range (6, 8):
if board[i][j] == num:
checkSM += 1
if subMatrix == 8:
for i in range (6, 8):
for j in range (6, 8):
if board[i][j] == num:
checkSM += 1
checkT = checkR + checkSM + checkC
if checkT == 0:
ok = True
return ok
def main ():
board = createBoard()
subma = defineSubMatrix(0, 6)
print (subma)
printBoard(board)
print ("Board Created")
level = createLevel(board)
print ("Level created")
printBoard(level)
###PROGRAMA
main()
You can't create a Sudoku this way, by just making random selections. You quickly get into a situation like this:
1 2 3 4 5 6 7 8 9
4 5 6 1 2 3 . . .
and now there are no possibilities for the next cells.
Many Sudoku algorithms create the grids the same way humans solve them, using complicated heuristics. It is possible to use brute force. Consider that every Sudoku puzzle can be derived from every other Sudoku puzzle, by using a combination of (a) swapping rows, (b) swapping columns, (c) swapping sets of 3 rows, (d) swapping sets of 3 columns, (e) rotating 90 degrees, and (f) mirroring across one of the axes. Given that, you can start with a well ordered matrix like this:
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 3 4 5 6 7 8 9 1
5 6 7 8 9 2 3 4 5
8 9 1 2 3 4 5 6 7
3 4 5 6 7 8 9 1 2
6 7 8 9 1 2 3 4 5
9 1 2 3 4 5 6 7 8
and then doing random swaps, rotates, and mirrors, just like shuffling a deck of cards. See this article:
https://www.algosome.com/articles/create-a-solved-sudoku.html

How can i print matrix[i][j] in python?

how can i print the matrix[i][j]?
from array import *
class Sudoku :
matrix = []
x = -1
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a)
except:
matrix.append(x)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])
error is :
print(matrix[i][j])
TypeError: 'int' object is not subscriptable
You can use this code if you want to complete the code with minimum number of lines but it sure is a bit complex.
m,n=input("Enter num of rows and columns:").split()
matrix=[[int(input()) for y in range(int(n))]for x in range(int(m))]
[[[print(matrix[i][j], end=" ") for j in range(int(n))] and print(" ") ]for i in range(int(m))]
The output looks like this:
Enter num of rows and columns: 3 3
1
2
3
4
5
6
7
8
9
1 2 3
4 5 6
7 8 9
from array import *
class Sudoku:
matrix = []
x = -1 # <--- 4
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a) # <--- 11
except: # <--- 12
matrix.append(x) # <--- 13
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j]) # <--- 16
Let's look at the code. If except at L12 is catched, x, which is -1 (L4) is appended. So at L16, when matrix[i] evaluates to -1, -1[j] is an error.
There's also another problem -- L11 will never be executed, because a is always a list, not int.
matrix = [] is declaring matrix to be a list. But you are thinking of the matrix as having i,j locations like in math.
You have two options:
Option1: Map the list to a matrix
If you have a 3x3 matrix you have 9 locations, so
matrix = [0, 1, 2, 3, 4, 5, 6, 7, 8] is equivalent to
0 1 2
matrix = 3 4 5
6 7 8
so if wanted to print out this matrix you have to do some math to access the elements
for i in range(3): # i = 0, 1, 2
for j in range(3): # j = 0, 1, 2
print(matrix[3*i + j], end=" ")
print("")
Option2: Make matrix be a nested list
have matrix becomes a list of row, and each row is a list of elements
matrix = []
x = -1
for i in range(0, 10):
row = []
for j in range(0, 10):
while True:
x = int(input(f"Enter matrix[{i}][{j}]} element: "))
if (isinstance(x, int)) == True :
row.append(x)
break;
matrix.append(row)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])

How to reflect a number output in Python?

I have a programm which draws a picture from numbers in certain way
n = int(input(" Введіть ваше число "))
m = n * 2 - 1
pp = " "
i = 0
while m != 0:
l = []
while m > n:
while i < n:
i += 1
j = n - i
k = i
while j != 0:
l.append(pp)
j -= 1
while k != 0:
l.append(str(k))
k -= 1
m -= 1
a = " "
print(a.join(l))
l = []
i = 0
OUTPUT:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
But now I get a task to draw this picture
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Is there any hint how to reflect it without overwriting the whole code?
For the output you are expecting, a very simple way to do it is with this code :
n = 5
for i in range(n):
print(' '.join([str(x+1) for x in range(i+1)]))
Output :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
You can try this. Its simple.
for i in range(1,n+1):
for j in range(1, i+1):
print(j, end="")
print()

How to write the following pattern

I am trying to print the following pattern in python but am not getting the desired output :
0
2 2
4 4 4
6 6 6 6
I have already used the following code but am not getting the desired output
n = int (input("Enter number : "))
for i in range (n):
print (i *2 )
Try this:
n = int (input("Enter number : "))
for i in range (n):
print (' '.join([str(i * 2) for _ in range(i + 1)]) )
You need to print the number i+1 times.
for i in range (n):
for _ in range(i+1):
print (i * 2," ", end='') # print without newlines
print() # end the line
Following simple code could help:
n = int (input("Enter number : "))
j = 1
k = 0
for i in range(n):
s = str(k)+' '
print(s*j)
j += 1
k += 2
if n = 4, then it would print the following :
0
2 2
4 4 4
6 6 6 6
n = int (input("Enter number : "))
count = 1
for i in range (n):
res = str(i*2) + " "
print (res * (i+1))
print n

Python Printing Matrix

Can you help me in how to print this on the right way? I've tried many ways but none work'd
while True:
m = int(input())
mlen = m
sm = 1
aux = 1
matriz = []
if m == 0:
print()
break
for i in range(m):
linha = []
for j in range(m):
linha.append(sm)
matriz.append(linha)
while m - 2 > 0:
for i in range(aux, m - 1):
for j in range(aux, m - 1):
matriz[i][j] = sm + 1
sm += 1
aux += 1
m -= 1
for i in matriz:
for j in i:
print('{:4}'.format(j), end='')
print('')
I have to print the matrix as the example below. It's an URI Online Judge exercise (num 1435). The dots below are spaces and I can't have any after the last element of the matrix.
Accepted Output Your Output
1 ··1···1···1···1 1 ···1···1···1···1
2 ··1···2···2···1 2 ···1···2···2···1
3 ··1···2···2···1 3 ···1···2···2···1
4 ··1···1···1···1 4 ···1···1···1···1
6 ··1···1···1···1···1 6 ···1···1···1···1···1
7 ··1···2···2···2···1 7 ···1···2···2···2···1
8 ··1···2···3···2···1 8 ···1···2···3···2···1
9 ··1···2···2···2···1 9 ···1···2···2···2···1
10 ··1···1···1···1···1 10 ···1···1···1···1···1
Thanks in advance.
Try using str.rjust(width[, fillchar]), you can then use the fillchar to get the dots
https://docs.python.org/3.6/library/stdtypes.html?highlight=rjust#str.rjust

Categories