Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need help creating a christmas tree using python

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:

enter image description here
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
                    *
                   ***
                  *****
                 *******
                *********
                 *******
                *********
               ***********
              *************
             ***************
              *************
             ***************
            *****************
           *******************
          *********************
           *******************
          *********************
         ***********************
        *************************
       ***************************
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading