I just started a python course in my university and need help solving an exercise. It is asking me to write a Christmas_tree(h,n,s) function that draws a christmas tree with the "*" character. The exercise requires to have a
- h: height level, number of lines in each level of the tree
- n: number of levels
- s: shifts in between each level of the tree and the next level in number of "*"
ex. Christmas_tree(5,4,2) will be represented as such:
>Solution :
Use two nested loops to handle the levels and the changes within each level, and use the str.center
method to center each row.
>>> def christmas_tree(h, n, s):
... max_width = 1 + 2 * h * n
... width = 1
... for _ in range(n):
... for _ in range(h):
... print(("*" * width).center(max_width))
... width += 2
... width -= 2 * s
...
>>> christmas_tree(5, 4, 2)
*
***
*****
*******
*********
*******
*********
***********
*************
***************
*************
***************
*****************
*******************
*********************
*******************
*********************
***********************
*************************
***************************