Printing an ASCII diamond with set width in python

2020-02-06 18:06发布

问题:

Yes, this is a homework task. But just please, if you're going to give me the code please tell me what you've done in detail. I am extremely new to this.

So the task is to print an ASCII diamond depending on what width the user inputs. I can do the first half of the diamond, just not the bottom half, for some reason I just cannot see how to do it.

Here's my code:

wid = int(input("Width: "))
i = 1

while i <= wid:
  print(" " * (wid - i) + "* " * i)
  i = i + 1

Which will output the following if wid = 5:

Width: 5
    * 
   * * 
  * * * 
 * * * * 
* * * * * 

回答1:

I tried to explain the code with comments. I hope it helps.

wid = int(input("Width: "))

#no. of lines will be double the width
#each loop prints a line.
for i in range(wid *2):

    #first half of the diamond
    if i<=wid:
        no_of_spaces = wid - i
        no_of_stars = i
        print(" "*no_of_spaces +  "* "*no_of_stars) 

    #next half of the diamond
    else:
        no_of_spaces = i - wid
        no_of_stars = 2*wid - i
        print(" "*no_of_spaces +  "* "*no_of_stars) 


回答2:

 i=1
 j=input("ENTER NO =")
 l=0
 for i in range(i,j-((j/2)-1),1):
     print (' ' * ((j+1)/2-i)+'*' *(i*2-1))
     l=(j/2+1)
     while  (i==l):
        i=1
        for i in range(i,j,1):
            print (' ' *((i*2)-i)+'*' *(j-i*2))
        if [i==j-1]:
            l=raw_input('<press enter to exit>')       


回答3:

You start with i = 1 and go until i > wid to make the top. To make the bottom of the diamond, you must do the reverse of what you did for the top. The code is easy, but I won't write it unless you want me to.



回答4:

after your while

i=i-2
while i>0:
  print(" "*(wid-i)+"* "*i)
  i=i-1;


回答5:

One method

The simplest way would probably be have two loops; one counting i up to width, another counting i back down to 1.

width = int(input("Width: "))

i = 1
while i < width:
    print " " * (width-i) + "* " * i
    i += 1

while i > 0:    
    print " " * (width-i) + "* " * i
    i -= 1

This is a bit unattractive because it's a little clumsy, but it's simple.


Another method

Another method is to have have a loop that counts to twice the width, doing one of two things. What it does depends on if i has passed the point of maximum width or not. So it does 'up' and 'down' in the same loop, counting i from 1 up to width*2.

width = int(input("Width: "))

i = 1
while i < width*2:
    if i < width:
        print " " * (width-i) + "* " * i
    else:
        print " " * (i-width) + "* " * (2*width-i)

    i += 1

This:

 print " " * (width-i) + "* " * i

...is your code. Spaces count from width down to 0, *'s from 1 up to width.

And this:

 print " " * (i-width) + "* " * (2*width-i)

...is the same thing but inverted. Spaces count from 0 back up to width, and the *'s go back down from width to 1. This comes into play when i exceeds width.

Width: 4
   *      # first half does this onward
  * * 
 * * * 
* * * * 
 * * *    # second half does the rest downward
  * * 
   * 

And another

Another alternative, more complex way is to use a for loop on a list that contains numbers counting up and down. For example: [1, 2, 3, 2, 1]

To make this list, this code has to be. I know, it's a bit ugly:

rows = []
for i in range(1, max+1):
    rows.append(i)
rows += rows[-2::-1]

Then, you see, we run the for loop off it.

width = int(input("Width: "))

rows = []
for i in range(1, width+1):
    rows.append(i)
rows += rows[-2::-1]    # takes a reversed list and adds it on to the end: [1, 2, 3, 2, 1]

for i in rows:
    print " " * (width-i) + "* " * i

i iterates through each of the numbers in the rows list, which looks something like [1, 2, 3, 2, 1]. Then we just need one printing gizmo.

In python, there's almost always a shorter and less comprehensible way of doing for loops, and in this case, we can get rid of two extra lines by shortening the first for loop:

width = int(input("Width: "))

rows = [ i for i in range(1, width+1)]  # Brain-bending way of doing a for loop 
rows += rows[-2::-1]

for i in rows:
    print " " * (width-i) + "* " * i

And if you're feeling a bit crazy, here's a mere two line version of the whole thing!

width = int(input("Width: "))
print "\n".join([ " "*(width-i) + "* "*i for i in [ i for i in range(1, width+1) ]+[ i for i in range(1, width+1) ][-2::-1] ])

But I don't recommend this style of coding in general.


Sorry, I got a bit carried away at the end... but the best thing I can say to you now is try everything and play around!

Hope that helps. :)



回答6:

Since some good methods have been addressed, here are some fun little hacky solutions.

Here's one using Python 2.7 string.center just for shits.

import string    

width = int(raw_input("Width:"))

for i in range(width):
    print string.center(i * " *", width * 2 )

for i in range(width,0,-1):
    print string.center(i * " *", width * 2 )

And here's an outrageous one that ouputs using HTML to center.

file = open('file.html','w')
file.write("<div align='center'>")

for i in range(width):
    file.write(i * " *") 
    file.write("<br>")

for i in range(width,0,-1):
    file.write(i * " *")
    file.write("<br>")

file.write("</div>")
file.close() 

import webbrowser
webbrowser.open("file.html")


回答7:

check it out (for python 2.7x) :


Filled ASCII Diamond :

width = 1
width += int(raw_input('Width : '))
for i in range (1,width):
    for j in range (width,i,-1):
        print " ",
    for j in range (1,i,1):
        print " * ",
    print

for i in range (width,1,-1):
    for j in range (width,i,-1):
        print " ",
    for j in range (1,i,1):
        print " * ",
    print

This works!! But not in any Browser window . . .



标签: python ascii