Creating a diamond pattern using loops

后端 未结 5 401
予麋鹿
予麋鹿 2021-01-03 17:17

I am trying to write a program that reads an integer and displays, using asterisks, a filled diamond of the given side length. For Example, if the side length is 4, the prog

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 17:46

    How about the following:

    side = int(input("Please input side length of diamond: "))
    
    for x in list(range(side)) + list(reversed(range(side-1))):
        print('{: <{w1}}{:*<{w2}}'.format('', '', w1=side-x-1, w2=x*2+1))
    

    Giving:

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

    So how does it work?

    First we need a counter that counts up to side and then back down again. There is nothing stopping you from appending two range lists together so:

    list(range(3)) + list(reversed(range(3-1))
    

    This gives you a list [0, 1, 2, 1, 0]

    From here we need to work out the correct number of spaces and asterisks needed for each line:

      *        needs 2 spaces 1 asterix
     ***       needs 1 space  3 asterisks
    *****      needs 0 spaces 5 asterisks
    

    So two formulas are needed, e.g. for side=3:

    x   3-x-1   x*2+1
    0   2       1
    1   1       3
    2   0       5
    

    Using Python's string formatting, it is possible to specify both a fill character and padding width. This avoids having to use string concatenation.

    If you are using Python 3.6 or later, you can make use of f string notation:

    for x in list(range(side)) + list(reversed(range(side-1))):
        print(f"{'': <{side - x - 1}} {'':*<{x * 2 + 1}}")
    

提交回复
热议问题