【问题标题】:Printing Numbers in X Shape pattern in python in increasing to decreasing order在python中以递增到递减的顺序打印X形模式中的数字
【发布时间】:2022-12-02 22:46:36
【问题描述】:

我正在用 python 解决一个模式问题,我需要以这样的方式打印一个模式,它由 X 组成,数字首先按递增顺序填充,然后在达到中间数字后,它们按递减顺序排列,

基本上我做了什么,我找到了X 将显示的区域。,并用空格填充剩余的矩阵..,

但它不符合我的模式..

Output Pattern image

这是我的方法:

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()

我想做的是: left diagonal and Right diagonal numbers :0 1 2 1 0 但我得到的是: left diagonal and Right diagonal numbers :0 1 2 3 4

【问题讨论】:

    标签: python python-3.x matrix


    【解决方案1】:

    这是一个更长的选择,但它确实有效。但是,当输入偶数时,您会遇到一个奇怪的问题。

    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])
    

    【讨论】:

    • 是的..我看到它在奇数时工作正常..,无论如何谢谢..我需要弄清楚这实际上发生在这里。
    • 在这里,我将添加评论以使其更容易。
    【解决方案2】:

    您可以打印 min(rows, n - rows - 1) 而不是 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()
    

    输出:

    0   0
     1 1 
      2  
     1 1 
    0   0
    

    对于n = 7-

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

    对于n = 6-

    0    0
     1  1 
      22  
      22  
     1  1 
    0    0
    

    【讨论】:

    • 好的..它适用于给定的测试用例..但对于其他数字,如 5 或 6 等,它正在形成不同的模式..
    • 它为所有奇数返回正确的模式。偶数的预期输出是多少。例如4/6?
    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多