Home > OS >  Printing Numbers in X Shape pattern in python in increasing to decreasing order
Printing Numbers in X Shape pattern in python in increasing to decreasing order

Time:12-03

I am solving a pattern problem in python, i need to print a pattern in such a way it consists of X and the numbers are filled first in increasing order and then after reaching mid number, they go to decreasing order,

basically i did what, i find out the area where the X will display.,and fill the remaining matrix with blank spaces..,

but it is not according to my pattern..

Output Pattern image

here is my approach:

n=int(input("Enter total rows"))
#n=5
for rows in range(n):
  for cols in range(n):
    if((rows == cols) or (rows cols)==n-1 ):
      print(rows,end="")
    else:
      print(" ",end="")
  print()

what i am trying to do is: left diagonal and Right diagonal numbers :0 1 2 1 0 but what i am getting is: left diagonal and Right diagonal numbers :0 1 2 3 4

CodePudding user response:

You can print the min(rows, n - rows - 1) instead of rows -

n = 5
for rows in range(n):
  for cols in range(n):
    if((rows == cols) or (rows cols)==n-1 ):
      print(min(rows, n - rows - 1),end="")
    else:
      print(" ",end="")
  print()

Output:

0   0
 1 1 
  2  
 1 1 
0   0

For n = 7 -

0     0
 1   1 
  2 2  
   3   
  2 2  
 1   1 
0     0

For n = 6 -

0    0
 1  1 
  22  
  22  
 1  1 
0    0

CodePudding user response:

This is a longer alternative, but it does work. However you will run into a weird issue when entering an even number.

n = int(input("Enter Total Rows: "))

matrix = []

# Append each row and column to the matrix.
for rows in range(n):
  row = []
  for cols in range(n):
    row.append(" ")

  matrix.append(row)

for i in range(n):
  if i > n/2:  # After we reach the center, start to subtract numbers instead of adding
    matrix[i][i] = abs(i - (n - 1))  # Abs is so we can invert the negative number to a positive
  else:
    matrix[i][i] = i

  if i > n/2:  # Ditto, but now instead of top left to bottom right, it goes top right to bottom left
    matrix[i][n - (i   1)] = abs(i - (n - 1))
  else:
    matrix[i][n - (i   1)] = i

# Print each row of the matrix
for i in range(len(matrix)):
  print(*matrix[i])
  • Related