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
167 views
in Technique[技术] by (71.8m points)

python - Draw an M-shaped pattern with nested loops

I just started Python 2.7 very recently, but I'm stuck at this a problem:

Make a program that prints an "M" pattern of asterisks. The user shall input the height of the pattern.

Here's the picture of the problem:

Image of problem description with sample output

h=raw_input("Enter the height of MStar here:")
h=int(h)

for row in range(0,(h-1)/2):
     for column in range(row+1):
         print "*",
    print
for row in range((h-1)/2,h):
    for column in range(h):
        print "^",
    print

It is also suggested that I can do two loops for the pattern because it can be seen as two parts, the upper one with the stars and spaces, and the second part that looks like a rectangle which I've done. I need some help with my code, because I really don't know how I can add the second triangle, I've can only make the first.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I imagine this problem as two triangles overlapping each other. You can write two functions that checks whether a coordinate is in a triangle. For example, this code

 for i in range(n):
   for j in range(n):
     if left(i,j):
       print '*',
     else:
       print '.',
   print

gives this output:

 * . . . . . .
 * * . . . . .
 * * * . . . .
 * * * * . . .
 * * * * * . .
 * * * * * * .
 * * * * * * *

Changing left to right gives the mirror image:

 . . . . . . *
 . . . . . * *
 . . . . * * *
 . . . * * * *
 . . * * * * *
 . * * * * * *
 * * * * * * *

Once you've figured out the correct implementation of left and right, just combine the two as left(i,j) or right(i,j) to get the M shape:

 * . . . . . *
 * * . . . * *
 * * * . * * *
 * * * * * * *
 * * * * * * *
 * * * * * * *
 * * * * * * *

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

...