Welcome to our community

Be a part of something great, join today!

Python : Explanation of code

mathmari

Well-known member
MHB Site Helper
Apr 14, 2013
4,922
Hey!! :giggle:

I found online the following code for a christmas tree in Python :
Code:
tree_height = input("Enter the tree height : ")
tree_height = int(tree_height)
spaces = tree_height-1
hashes = 1
stump_spaces = tree_height-1

while tree_height != 0 :
    for i in range(spaces):
        print(' ', end="")
    for i in range(hashes):
        print('#', end="")
    print()
    tree_height -= 1
    spaces -= 1
    hashes += 2
for i in range(stump_spaces):
    print(' ', end="")
print('#',end="")
Could you explain to me why the "spaces" is at the beginning equal to "tree_height-1" ? Shouldn't it be the half of that? :unsure:
 

Jameson

Administrator
Staff member
Jan 26, 2012
4,093
What do you think the spaces value should be? $\displaystyle \frac{h-1}{2}$?
 

mathmari

Well-known member
MHB Site Helper
Apr 14, 2013
4,922
What do you think the spaces value should be? $\displaystyle \frac{h-1}{2}$?
When the spaces is equal to the height doesn't the tree start from the left end instead in the middle? :unsure:
 

Ackbach

Indicium Physicus
Staff member
Jan 26, 2012
4,203
The tree width at the next-to-bottom row is twice the height. So, if you entered '20' at the input line, the first row would have one symbol, the second row would have 3, the third row would have 5, and so on. The second-to-last row will have 39 symbols, not 20 or 19 or 21.
 

mathmari

Well-known member
MHB Site Helper
Apr 14, 2013
4,922
The tree width at the next-to-bottom row is twice the height. So, if you entered '20' at the input line, the first row would have one symbol, the second row would have 3, the third row would have 5, and so on. The second-to-last row will have 39 symbols, not 20 or 19 or 21.
So the number of symbols is $2i-1$ for the line $i$, right? I haven't really understood the formula for the spaces. Could you explain that further to me ? :unsure: