如何将这两个形状对齐以形成一棵树?

2024-05-06 04:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要打印一个树形,其中用户输入4个不同的参数。枝高、枝宽、茎高、茎宽。我有两个形状,形成了树的顶部和底部,但我似乎不知道如何把它们放在一起,使它看起来像一棵树。我想我需要计算出树枝的宽度,并从中扣除树干的宽度,但我不太确定。我的输出当前如下所示:

有什么建议吗?你知道吗

Enter height of the branches: 5
     *
    ***
   *****
  *******
 *********
Enter width of the stem: 5
*****
*****
*****
*****
*****



def pyramid(height):
    for row in range(height):
        for count in range(height - row):
            print(end=" ")
        for count in range(2 * row + 1):
            print(end="*")
        print()

def square(width):
    for i in range(width):
        for j in range(width):
            print('*', end='')
        print()


height = int(input("Enter height of the branches: "))
pyramid(height)

width = int(input("Enter width of the stem: "))
square(width)

Tags: oftheinfor宽度defrangewidth
3条回答

你可以试试这个:

    def pyramid(height):
        for row in range(height):
            for count in range(height - row):
                print(end=" ")
            for count in range(2 * row + 1):
                print(end="*")
            print()

    def square(width):
        if height % 2 == 0:
         space=int((height/2))*' '
        else:
         space=int((height/2)+1)*' '
        for i in range(width):
            print(end=space)
            for j in range(width):
                print('*', end='')
            print()


    height = int(input("Enter height of the branches: "))


    width = int(input("Enter width of the stem: "))
    pyramid(height)
    square(width)

您正在寻找^{}

def pyramid(height):
    for row in range(height):
        print(('*' * (2 * row + 1)).center((2 * height + 1)))

def square(width, height):
    for i in range(width):
        print(('*' * (width)).center((2 * height + 1)))

height = int(input("Enter height of the branches: "))
pyramid(height)

width = int(input("Enter width of the stem: "))
square(width, height)

输出:

C:\_\Python363-64\python.exe C:/Users/MrD/.PyCharm2018.2/config/scratches/scratch_75.py
Enter height of the branches: 5
     *     
    ***    
   *****   
  *******  
 ********* 
Enter width of the stem: 5
   *****   
   *****   
   *****   
   *****   
   *****   

Process finished with exit code 0

您可以在每行杆之前添加空格,这些空格足以填充棱锥体的高度减去杆的一半宽度:

def pyramid(height):
    for row in range(height):
        for count in range(height - row):
            print(end=" ")
        for count in range(2 * row + 1):
            print(end="*")
        print()

def square(width, pyramid_height):
    for i in range(width):
        print(' ' * (pyramid_height - width // 2), end='')
        for j in range(width):
            print('*', end='')
        print()


height = int(input("Enter height of the branches: "))
pyramid(height)

width = int(input("Enter width of the stem: "))
square(width, height)

相关问题 更多 >