Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backwards looping, creating a diamond pattern

I made a program that allows the user to type in the height of a diamond and it will print one out in asterisks using loops. My code now looks like this:

diamond = int(input("Height": )

for i in range(diamond-1):
    print((diamond-i) * " " + (2*i+1) * "*")
for i in range(diamond-1, -1, -1):
    print((diamond - i) * " " + (2 * i + 1) * "*")

And the diamond will look perfect like this (diamond == 6):

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

Now if I make some changes and instead write the backwards loop like this:

for i in reversed(range(diamond-1)):
    print((diamond - i) * " " + (2 * i + 1) * "*")

It will print out the diamond like this:

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

So my question is: what is the difference between the first backwards loop and the second one I wrote? Why do they turn out so different?

like image 827
John Long Silver Avatar asked Sep 07 '25 11:09

John Long Silver


1 Answers

Because they are different ranges:

>>> diamond = 6
>>> range(diamond-1, -1, -1)
[5, 4, 3, 2, 1, 0]
>>> list(reversed(range(diamond-1)))
[4, 3, 2, 1, 0]

range includes the start point, but excludes the end point.

like image 66
wim Avatar answered Sep 10 '25 03:09

wim