python
a) Write a function, hailstone(), that takes an integer value n as
a parameter,
and displays the hailstone sequence for the given integer. The
hailstone sequence
is determined as follows: if the value is even, divide by 2 (floor
division) or if the
value is odd, calculate 3 * n + 1. The function should display each
value and
continue updating the value until it becomes 1.
b) Write a program to display the hailstone sequence of all
integers between 5
and 10.
Sample Run:
5 16 8 4 2 1
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
and also write a
docstring comment for it
Please find the code, inline comments and output below.
a)
def hailstone(number,steps = 0):
print(number, end = " ");
if (number == 1 and steps == 0):
return steps;
elif (number == 1 and steps != 0):
steps = steps + 1;
elif (number % 2 == 0):
# If number is Even.
steps = steps + 1;
steps = hailstone(int(number / 2), steps);
elif (number % 2 != 0):
# If number is Odd.
steps = steps + 1;
steps = hailstone(3 * number + 1, steps);
return steps;
# Driver Code
number= int(input("Enter the number : "));
# Function call to generate Hailstone Numbers
x = hailstone(number);
b)
Write a program to display the hailstone sequence of all integers between 5 and 10.
''' Program to display the hailstone sequence of all integers
between 5 and 10 '''
def hailstone(number,steps = 0):
print(number, end = " ");
if (number == 1 and steps == 0):
return steps;
elif (number == 1 and steps != 0):
steps = steps + 1;
elif (number % 2 == 0):
# If number is Even.
steps = steps + 1;
steps = hailstone(int(number / 2), steps);
elif (number % 2 != 0):
# If number is Odd.
steps = steps + 1;
steps = hailstone(3 * number + 1, steps);
return steps;
# Driver Code to display the hailstone sequence of all integers
between 5 and 10
number=5
while(number<11):
print( "\nHailstone Numbers Sequences for "+str(number)+" is :
")
# Function call to generate Hailstone Numbers
x = hailstone(number);
number +=1
Get Answers For Free
Most questions answered within 1 hours.