打印知道长度和宽度的钻石 (Python)

Print diamond knowing length and width (Python)

我需要使用 python 打印钻石,方法是输入长度。我已经让它根据宽度是奇数还是偶数来检查宽度,同时确保输入的数字是正确的。但是当它打印结果时我遇到了问题。 这是我得到的:

length : 10

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


length = 10   #This line don't exist normally, its just to avoid the input and every check.
lengthTest = length
answer = lengthTest % 2
if (answer == 0):
    length_1 = 1
    while (length_1 < length):
        print("*" * length_1)
        length_1 = length_1 + 2
    length_1 = length_1 - 2
    while (length_1 > 0):
        print("*" * length_1)
        length_1 = length_1 - 2

else:
    print("odd")

space 问题的任何解决方案,使其看起来像钻石?

在星号前打印空格:

length = 10
x = 1
while x < length:
    print(" " * ((length - x) // 2), "*" * x)
    x += 2
x -= 2
while x > 0:
    print(" " * ((length - x) // 2), "*" * x)
    x -= 2

输出

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

你还需要在前面加上一半length-length_1个空格:

length = 10   #This line don't exist normally, its just to avoid the input and every check.
lengthTest = length
answer = lengthTest % 2
if (answer == 0):
    length_1 = 1
    while (length_1 < length):
        print(" " * ((length - length_1)//2) + "*" * length_1)
        length_1 = length_1 + 2
    length_1 = length_1 - 2
    while (length_1 > 0):
        print(" " * ((length - length_1) // 2) + "*" * length_1)
        length_1 = length_1 - 2

else:
    print("odd")

为什么要使用多个 for 循环?

for i in range(-n + 1, n):
    print('{:^{}}'.format('*' * ((n - abs(i)) * 2 - 1), n * 2 - 1))
  • 如果你想要半码,在循环之前设置n = n // 2

这是数学:

每次我们得到 +2 个星号,我们希望它们上升直到我们到达中心然后下降,所以我们从 -n+1 迭代到 n-1 并计算星号乘以 n 减去绝对当前索引(以提供 [-n, -1][1, n] 之间的反向对称)乘以二,减去一以创建 center-able 菱形(奇数长度) .

我们使用 ^{}n * 2 - 1 以字符串格式居中,因为这是可能的最大宽度(当 i = 0(n - abs(i)) * 2 - 1 将是 n * 2 - 1).

输出(对于n = 5):

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