有人可以帮助我制作带圈的菱形吗? (蟒蛇)

时间:2020-10-06 04:13:55

标签: python

n=3
   *
  * *
 *   *
  * *
   *

n=5
    *    
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *

我尝试了这个,但是我不使用n = 3或n = 5

for row in range(5):
    for col in range(5):
        if row+col==2 or col-row==2 or row-col==2 or row+col==6:
            print("*",end="")
        else:
            print(end=" ")
    print()

当我运行它时

  *  
 * *
*   *
 * *
  *

我需要制作带环的菱形,但是我真的是python的新手,有人可以帮我吗? 预先感谢!

1 个答案:

答案 0 :(得分:1)

这是此函数的一般形式,它采用n并生成与问题中显示的两个以及所有其他大小匹配的菱形:

def diamond(n):
    print("n=" + str(n))
    nn = 2 * n - 1
    for row in range(nn):
        for col in range(nn):
            if row+col==n-1 or col-row==n-1 or row-col==n-1 or row+col==3*(n-1):
                print("*",end="")
            else:
                print(end=" ")
        print()

diamond(3)
diamond(5)
diamond(7)

结果:

n=3
  *  
 * * 
*   *
 * * 
  *  
n=5
    *    
   * *   
  *   *  
 *     * 
*       *
 *     * 
  *   *  
   * *   
    *    
n=7
      *      
     * *     
    *   *    
   *     *   
  *       *  
 *         * 
*           *
 *         * 
  *       *  
   *     *   
    *   *    
     * *     
      *