2018-02-12 HW

posted Feb 11, 2018, 7:02 PM by Konstantinovich Samuel

Goal: Generating a sequence with a loop.


Notes on the print primitive:
You can print with a comma at the end of the line to prevent the new line from printing
e.g.
print 5,    #the next print is on the same line
print 6
print 7

outputs:
5 6
7

print 1
print 2,    #the next print is on the same line
print 3
print 4

outputs:
1
2 3
4


You can also separate values and print multiple things in one print statement:
print 5, 6

outputs:
5 6

print 5, 6
print 7
print 8,9

outputs:
5 6
7
8 9




Classwork:
The hailstone sequence starts at any natural number (positive integer), and always terminates with the value 1.
To generate the sequence you follow a simple set of rules:

if n = 1 : done
if n is even: the next number is n / 2
if n is odd: the next number is 3 * n + 1

So hailstone sequences starting with the first 6 values:
n:  sequence
1:  1
2:  2 1 
3:  3 10 5 16 8 4 2 1
4:  4 2 1
5:  5 16 8 4 2 1
6:  6 3 10 5 16 8 4 2 1
...


1. Write a function printHail(n) that will print the hailstone sequence (on one line for readability)
(Normally we don't print out things, instead we return them.  Since we know the starting/ending number of each sequence, it isn't a useful thing to return either. )





Once you complete the function that prints the sequence, we can move on to returning something again. 
Something we cannot predict is the length of the sequence!
2. Write a function that calculates the length of a hailstone sequence that starts with n: 
(look at the example sequences above to see why!) 
n ->  hailLen(n)
1 -> 1
2 -> 2
3 -> 8
4 -> 3
5 -> 6
6 -> 9
...


Homework:
Complete the hailstone problems on codingbat (under http://codingbat.com/home/konstans@stuy.edu/all  )

Comments