For the problem given:
Douglas Hofstadter’s Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle.
Pick a positive integer \$n\$ as the start.
If \$n\$ is even, divide it by 2.
If \$n\$ is odd, multiply it by 3 and add 1.
Continue this process until \$n\$ is 1.The thesis is: The number \$n\$ will travel up and down but eventually end at 1 (at least for all numbers that have ever been tried -- nobody has ever proved that the sequence will terminate). Analogously, hailstone travels up and down in the atmosphere before eventually landing on earth.
The sequence of values of n is often called a Hailstone sequence, because hailstones also travel up and down in the atmosphere before falling to earth. Write a function that takes a single argument with formal parameter name \$n\$, prints out the hailstone sequence starting at \$n\$, and returns the number of steps in the sequence.
Hailstone sequences can get quite long! Try 27. What's the longest you can find? Fill in your solution below:
def hailstone(n):
"""Print the hailstone sequence starting at n and return its length.
>>> a = hailstone(10) # Seven elements are 10, 5, 16, 8, 4, 2, 1
10
5
16
8
4
2
1
>>> a
7
"""
"*** YOUR CODE HERE ***"
Below is the solution written for above problem that performs hailstone sequence:
def hailstone(n):
count = 1
"""Print the terms of the 'hailstone sequence' from n to 1."""
assert n > 0
print(n)
if n > 1:
if n % 2 == 0:
count += hailstone(n / 2)
else:
count += hailstone((n * 3) + 1)
return count
result = hailstone(10)
print(result)
With the above solution, I would like to confirm that this program follows functional paradigm instead of imperative paradigm with good abstraction.
I would like to understand if this program can still be improved from paradigm perspective.
UnboundLocalError: local variable 'count' referenced before assignment
\$\endgroup\$global count
to fix the error... \$\endgroup\$global
keyword \$\endgroup\$