在python中打印一个数字菱形

时间:2018-01-25 16:25:00

标签: python

      1
     121
    12321
   1234321
  123454321
   1234321
    12321
     121
      1

我只能打印星星,但没有数字逻辑。

userInput = int(input("Please input side length of diamond: "))

if userInput > 0:
    for i in range(userInput):
        for s in range(userInput -3, -2, -1):
            print(" ", end="")
        for j in range(i * 2 -1):
            print("*", end="")
        print()
    for i in range(userInput, -1, -1):
        for j in range(i * 2 -1):
            print("*", end="")
        print()

2 个答案:

答案 0 :(得分:2)

您应该使用一些工具,例如str.centermapstr.joinitertools.chain

from itertools import chain

def up_and_down(n):  # 1,2, ..., n, ..., 2, 1
    return chain(range(1, n), range(n, 0, -1))

def diamond(n):
    for i in up_and_down(n):
        print((n-i)*' ', *up_and_down(i), sep='') 
        # or more performant
        # print(''.join(map(str, up_and_down(i))).center(2*n-1))

>>> diamond(5)
    1    
   121   
  12321  
 1234321 
123454321
 1234321 
  12321  
   121   
    1    

答案 1 :(得分:0)

对于范围 (1,6) 中的 i:

for j in range(6-i):
    print(" ", end=" ")

for k in range(1,i):
    print(k, end = " ")

for l in range(i, 0, -1):
    print(l, end= " ")


print() 

对于范围 (4,0,-1) 中的 i: 对于范围内的 j(6-i): 打印(" ", end="")

for k in range(1,i):
    print(k, end = " ")

for l in range(i, 0, -1):
    print(l, end= " ")
print()