How to recreate pyramid triangle?

后端 未结 3 635
野性不改
野性不改 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条回答
  •  臣服心动
    2020-12-07 05:53

    If you need to do a pyramid recursively you probably need to do something like this.

    def asterix_triangle(i, t=0):
        if i == 0:
            return 0
        else:
            print ' ' * ( i + 1 ) + '*' * ( t * 2 + 1)
            return asterix_triangle(i-1, t + 1)
    
    asterix_triangle(5)
    

    The idea is that you use two variables. One which is i that that subtract once every time the function is called and is used to end the cycle. The other variable is used to have an incremental increase. You then use i to print the number of spaces, and t the number of stars.

    The output would be:

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

提交回复
热议问题