简体   繁体   English

如何在 python 中打印金字塔 - 验证

[英]How to print pyramid in python - verification

I have a little slight confusion, below pattern is printed by adding 3 spaces with '* '.我有点困惑,下面的图案是通过添加 3 个空格和 '*' 来打印的。 Is it a right approach to do?这是正确的做法吗?

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

Code:代码:

for row in range(1,5+1):
  print(' ' * (5-row)*2 + row * '*   ')

Or i need to follow any different approach to print it.或者我需要遵循任何不同的方法来打印它。 Suggest me some other approach?建议我一些其他的方法?

If your task is to print the pyramid that you have shown - yes, you chose a correct approach.如果您的任务是打印您展示的金字塔 - 是的,您选择了正确的方法。

If you want to make the code a little bit more flexible and reusable, you cant put the logic into a function.如果你想让代码更灵活和可重用一点,你不能把逻辑放到 function 中。 I suggest print_pyramid .我建议print_pyramid After realizing that the number 5 is just the height of the pyramid you can replace 5 with a variable height and provide it as an argument to the function.在意识到数字 5 只是金字塔的高度后,您可以将5替换为可变height ,并将其作为参数提供给 function。

For good measure I would do the same with the padding (three blanks) and the marker '*' .为了更好地衡量,我会对填充(三个空格)和标记'*'做同样的事情。

The final print statement first looked like最终的打印语句首先看起来像

print(" " * (height - row) * padding + row * cell)

which can be expressed with an f-string as可以用 f 字符串表示为

print(f'{" " * (height - row) * padding}{row * cell}')

I prefer f-strings whenever I encounter string-concatenation as I consider them more readable.每当我遇到字符串连接时,我更喜欢 f-strings,因为我认为它们更具可读性。

In sum I would suggest the following总之,我建议以下

def print_pyramid(height, padding=3, marker="*"):
    padding_ws = " " * (padding * 2 - 1)
    cell = marker + padding_ws
    for row in range(1, height + 1):
        print(f'{" " * (height - row) * padding}{row * cell}')


if __name__ == '__main__':
    print_pyramid(height=5)

Note that you can now also generate variants of your pyramid like print_pyramid(7, padding=2, marker="x") .请注意,您现在还可以生成金字塔的变体,例如print_pyramid(7, padding=2, marker="x")

This is a general solution which takes advantage of the simmetry of the tree:这是利用树的对称性的一般解决方案:

c = [" ", "*"]

def print_pyramid(n_layers):
    n = (n_layers * 2 - 1)
    s = " " * n
    for x in range(n_layers + 1):
        s = (s + " " + c[int(x%2)])[-n:]
        print(s + s[:-1][::-1])

So for example:例如:

print_pyramid(5)

OUTPUT OUTPUT

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

or或者

print_pyramid(10)

OUTPUT OUTPUT

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

The solution is focused in building half of the tree, given its symmetry:鉴于树的对称性,该解决方案的重点是构建树的一半:

  • The user inputs the number of layers" in the pyramid用户在金字塔中输入“层数”
  • Given that number of layers, the size of the base can be worked out: for example, if a pyramid has 2 layers, the base will be 5 characters wide;给定层数,就可以计算出底部的大小:例如,如果金字塔有 2 层,则底部将是 5 个字符宽; if, as in the question, there are 5 layers, the base will be 17 wide.如果像问题中那样,有 5 层,则底座将是 17 宽。 In general, the size of the base will be (n_layers - 1) * 4 + 1一般来说,base 的大小为(n_layers - 1) * 4 + 1
  • Half a pyramid - including the central symmetry lines - will be n = (n_layers - 1) * 2 + 1 = n_layers * 2 - 1半个金字塔 - 包括中心对称线 - 将是n = (n_layers - 1) * 2 + 1 = n_layers * 2 - 1
  • We take advantage to this property in the loop - where in each iteration we append a space and, in turns, a space or an asteristik (note that int(x%2) will return a 0 if the loop is even, 1 otherwise)我们在循环中利用了这个属性 - 在每次迭代中,我们 append 一个空格,然后是一个空格或一个星号(请注意,如果循环是偶数,则int(x%2)将返回 0,否则返回 1)
  • We then print this half pyramid and its reverse, dropping the centre given that we don't won't to print it twice然后我们打印这个半金字塔及其反面,放弃中心,因为我们不会打印两次

Yes your logic work's.是的,你的逻辑工作。 One benefit about your code is that you can print different variant's of pyramids.您的代码的一个好处是您可以打印不同的金字塔变体。

Make your code a generic, so that it can be used for any number of input使您的代码具有通用性,以便它可以用于任意数量的输入

If required different variant of pyramid you can change the ljust value from 4 to any other number.如果需要不同的金字塔变体,您可以将ljust值从4更改为任何其他数字。

Code:代码:

def print_pyramid(n):
  for row in range(1,n+1):
    print(' ' * (n-row)*2 + row * '*'.ljust(4))

print_pyramid(10)

Output: Output:

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

You could make fewer calculations by altering a string at each iteration to adjust it for the indent and extra star before printing:您可以通过在每次迭代中更改字符串以在打印前调整其缩进和额外星号来减少计算量:

n = 5
row = "  "*(n-1)
for _ in range(n):
    row = row[2:]+"   *"
    print(row)

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

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

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