How to recreate pyramid triangle?

2019-01-15 22: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.

As an example this is a 4 line asterisk triangle.

     *
    **
   ***
  ****

I have tried this function:

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

And the following function:

def asterisk_triangle(rows=n):
    pyramid_width = n * 2
    for asterisks in range(1, pyramid_width, 2):
        print("{0:^{1}}".format("*" * asterisks, pyramid_width))

And neither worked. I am supposed to make tests.py to test the functions and I get errors for e.g

Traceback (most recent call last):
  File "C:\Users\akumaukpo\Documents\CISC 106\LAB05\lab05 _test.py", line 19, in <module>
    from lab05 import *
  File "C:\Users\akumaukpo\Documents\CISC 106\LAB05\lab05.py", line 22
    print i
        ^

回答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:

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)
    *
   ***
  *****
 *******


回答2:

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:

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


回答3:

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

The output is as shown in the link