Draw an M-shaped pattern with nested loops

前端 未结 4 1143
慢半拍i
慢半拍i 2020-12-12 02:11

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 in

4条回答
  •  無奈伤痛
    2020-12-12 02:38

    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:

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

提交回复
热议问题