Skip to content Skip to sidebar Skip to footer

How To Recreate Pyramid Triangle?

I have to write a recursive function asterisk_triangle which takes an integer and then returns an asterisk triangle consisting of that many lines. As an example this is a 4 line as

Solution 1:

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:

defasterix_triangle(depth):
        rows = [ (depth-i)*' ' + i*'*' + '*'for i inrange(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:

defasterix_triangle(depth):
        rows = [ (depth-i)*' ' + i*'*' + '*' + i*'*'for i inrange(depth) ]
        for j in rows:
            print j

The output:

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

Solution 2:

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

defasterix_triangle(i, t=0):
    if i == 0:
        return0else:
        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:

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

Solution 3:

for i in range(10):
print((' '*(10-i-1))+(('*')*((2*i)-1)))

The output is as shown in the link

Post a Comment for "How To Recreate Pyramid Triangle?"