How to recreate pyramid triangle?

后端 未结 3 630
野性不改
野性不改 2020-12-07 05:12

I have to write a recursive function asterisk_triangle which takes an integer and then returns an asterisk triangle consisting of that many lines.

3条回答
  •  -上瘾入骨i
    2020-12-07 05:42

    Every statement in a block must be indented by at least one space from the start of the block. The print statement in your code is not indented relative to the for block it is contained in, which is why you have the error.

    Try this:

    def asterix_triangle(depth):
            rows = [ (depth-i)*' ' + i*'*' + '*'   for i in range(depth) ]
            for i in rows:
                print i
    

    Which yields:

    >>> asterix_triangle(4)
        *
       **
      ***
     ****
    

    EDIT:

    I just realised your desired output is to have both halves of a triangle. If so, just mirror the string by adding the same thing to the right side of the string:

    def asterix_triangle(depth):
            rows = [ (depth-i)*' ' + i*'*' + '*' + i*'*'  for i in range(depth) ]
            for j in rows:
                print j
    

    The output:

    >>> asterix_triangle(4)
        *
       ***
      *****
     *******
    

提交回复
热议问题