Utopian Tree : HackerRank Solution in Python
The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter.
A Utopian Tree sapling with a height of 1 meter is planted at the onset of spring. How tall will the tree be after growth cycles?
For example, if the number of growth cycles is n=5, the calculations are as follows:
Complete the utopianTree function in the editor below.
utopianTree has the following parameter(s):
- int n: the number of growth cycles to simulate
- int: the height of the tree after the given number of cycles
Solution in Python 3
As per the challenge, A Utopian Tree sapling is planted with a height of 1 meter. To represent that we will name a variable height and initialize it to 1.
height = 1
To simulate the growth cycles of magnitude n, which is given as input we will use a for loop:-
for growthCycle in range(1, n+1):
As the growth cycles start from 1 and and up to the nth value we substitute 1 and n+1 in range function.
As the Utopian Tree is planted on the onset of spring the 1st growth cycle will be spring & as there are only two cycles all odd growth cycles will be of spring. Thus to represent that we will double the height if growthCycle is odd.
Similarly, the 2nd growth cycle will be Summer and thus every even growth cycle will also be Summer. As we already check whether the growthCycle is odd, the remainder of the cases will be even and thus we will use an else statement and increment the height by 1 at such cases.
at the end of code we will return the height.
The full solution is:-