Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

python - 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 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:UsersakumaukpoDocumentsCISC 106LAB05lab05 _test.py", line 19, in <module>
    from lab05 import *
  File "C:UsersakumaukpoDocumentsCISC 106LAB05lab05.py", line 22
    print i
        ^
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...