Why is spaces equal to tree_height-1 in the Christmas tree code in Python?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
mathmari
Gold Member
MHB
Messages
4,984
Reaction score
7
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:
 
on Phys.org
Jameson said:
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:
 
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.
 
Ackbach said:
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:
 
mathmari said:
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:
Yes, that's right!

spaces is initially equal to tree_height - 1, because tree_height is roughly half the horizontal distance from the far left to the far right on the second-to-last row. You want to "put your cursor" ready-to-print right before the exact character you need to print, hence the -1.