简体   繁体   English

如何在 Python 中打印金字塔?

[英]How to print a pyramid in Python?

How to make a pyramid?如何制作金字塔?

I need to make a function, that prints a full pyramid.我需要制作一个 function,它可以打印一个完整的金字塔。

For example例如

(13 is the base width of the pyramid and 1 is the width of the top row.) (13 是金字塔的底边宽度,1 是顶行的宽度。)

pyramid(13, 1)

Result:结果:

       .

     .....

   .........

 ............. 

The step should be 4, so each row differs from the last row by 4 dots.步长应为 4,因此每行与最后一行相差 4 个点。

Edit:编辑:

This is what I have so far, but I only got the half of the pyramid and the base isn't what it's supposed to be.这是我到目前为止所拥有的,但我只得到了金字塔的一半,而底部不是它应该的样子。

def pyramid(a, b):
    x = range(b, a+1, 4)
    for i in x:
        print(" "*(a-i) + "."*(i))

pyramid(17,1)

Try this:尝试这个:

def pyramid(a, b):
    for i in range(b,a+1,4) :
        print(str( " " *int((a-i)/2) )+ "."*(i)+ str( " " *int((a-i)/2) ))

Output: Output:

pyramid(17,1)

        .        
      .....      
    .........    
  .............  
.................

Here is my contribution, using - character instead of blank space, for a better visualization:这是我的贡献,使用-字符而不是空格,以获得更好的可视化:

def pyramide(base, top, step=4):
    dot = "."
    for i in range(top, base+1, step):
        print((dot*i).center(base, "-"))

pyramide(13,1)

Output Output

------.------
----.....----
--.........--
.............
# Function to demonstrate printing pattern triangle 
def triangle(n): 

    # number of spaces 
    k = 2*n - 2

    # outer loop to handle number of rows 
    for i in range(0, n): 

        # inner loop to handle number spaces 
        # values changing acc. to requirement 
        for j in range(0, k): 
            print(end=" ") 

        # decrementing k after each loop 
        k = k - 1

        # inner loop to handle number of columns 
        # values changing acc. to outer loop 
        for j in range(0, i+1): 

            # printing stars 
            print("* ", end="") 

        # ending line after each row 
        print("\r") 

# Driver Code 
n = 5
triangle(n) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM