在Python 3中打印简单的菱形图案

时间:2018-04-08 17:33:29

标签: python python-3.x

我想在Python 3中打印这种模式(我是初学者):
Rhombus image

我尝试了什么:

n = 5

for x in range(1, (n+5) //2 + 1):
    for y in range( (n+5) //2 - x):
        print(" ", end = "")
    for z in range( (x*2)-1 ):
        print("*", end = "")
    print()

for x in range( (n+5)// 2 + 1, n + 5):
    for y in range(x - (n+5) //2):
        print(" ", end = "")
    for z in range( (n+5 - x) *2 - 1):
        print("*", end = "")
    print()

但结果是这样的:
Rhombus

如何使图像中间凹陷?

感谢。

3 个答案:

答案 0 :(得分:2)

空心菱形上的点的坐标满足|x|+|y|==m(其中m = n-1)。因此,您可以使用

In [29]: m = n-1; print('\n'.join([''.join(['*' if abs(row)+abs(col)==m else ' ' for col in range(-m,m+1)]) for row in range(-m,m+1)]))
    *    
   * *   
  *   *  
 *     * 
*       *
 *     * 
  *   *  
   * *   
    *    

或等效地,但没有list comprehensions

n = 5
m = n-1
for row in range(-m, m+1):
    for col in range(-m, m+1):
        if abs(row) + abs(col) == m:
            c = '*'
        else:
            c = ' '
        print(c, end='')
    print()

要制作实体菱形,只需将条件更改为abs(row) + abs(col) <= m

答案 1 :(得分:0)

使用递归:

def print_stars(i,n):
    if i:
        print( ' '*(n-i-1)  + '*' + ' '*(2*i-1) + '*')
    else:
        print( ' '*(n-1)  + '*')

# recursive
def r(n, i=0):
    print_stars(i,n) # up
    if i<n-1:
        r(n, i+1) # recurse
        print_stars(i,n) # down

# start
r(5)

打印:

    *
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *

答案 2 :(得分:0)

不使用函数的简单python代码

rows = 7

for i in range(1, rows + 1):
    for j in range(1, rows - i + 1):
        print(end = ' ')
    for k in range(1, 2 * i):
        if k == 1 or k == i * 2 - 1:
            print('*', end = '')
        else:
            print(' ', end = '')
    print()

for i in range(rows - 1, 0, -1):
    for j in range(1, rows - i + 1):
        print(' ', end = '')
    for k in range(1, 2 * i):
        if k == 1 or k == i * 2 - 1:
            print('*', end = '')
        else:
            print(' ', end = '')
     print()

输出:

      *
     * *
    *   *
   *     *
  *       *
 *         *
*           *
 *         *
  *       *
   *     *
    *   *
     * *
      *