2017-03-22 HWList

posted Mar 22, 2017, 7:00 AM by Samuel Konstantinovich   [ updated Mar 22, 2017, 8:49 AM ]
Do Now:
1. On paper, write a hailLen(n) function, that calculates the length of a hailstone sequence starting with n.
hailLen(1) -> 1
hailLen(2) -> 2
hailLen(3) ->  8   //because 3 10 5 16 8 4 2 1

Recall that the next number hailstone sequence is calculating by looking at the current number Hn
When Hn is 1:
     there is no next number.
When Hn is even:
    H(n+1) = Hn / 2
When Hn is odd:
    H(n+1) = 3 * Hn + 1 

Write a recursive method to solve this problem in your notebook. Then compare with your neighbors.


Lists
A list object is a collection of values. The list can contain 0 or more elements, and it can be modified (unlike strings).
We use [] square brackets to designate lists. 
The len() primitive works on lists just like strings.
We place a zero-based index inside the brackets to access/modify an individual position in the list.

y = []

     store the empty list into y.

x = [ 1, 5, 3, 9, 2]

    Store a list in variable x.

print x
    displays [1,5,3,9,2]     

print x[1]      (access a single value)
    displays 5 

x[2]=18         (modify a single value)
    Updates/modifies the list such that the 3 is replaced with 18.

Slices work the same way as before, except they return a COPY of the sub-list. 


x = [ 1, 5, 3, 9, 2]

print x[1:3]     
    displays [5,3]

print x[:4]     
    displays [1,5,3,9]

print x[::2]     
    displays [1,3,2]

You CAN assign to a slice or replace a slice with another list/slice! (examples tomorrow)


List Methods

A list object has a number of member methods.  

The following list transformation functions update a list object. In the case of the pop method, it both returns information as well as updates/modifies the list.

Classwork: (complete for homework)
In a python terminal test each of the five methods. Then in your notebook, write the method and describe exactly what it does, you may write an example of how it is used.

l.append ( object )
l.extend ( list )
l.insert ( index , object )
l.pop ( index ) → item
l.remove ( value ) 

Discuss with your neighbors so you can see if you have the right idea about how these work. 
Did you test many cases? (empty lists, 0's, values that aren't there, etc)
You MUST see what parameters are valid or invalid through experimentation.


HW LIST: (you will need a working copy in class tomorrow) 
1. Make a function that returns a list of n even integers starting with 0. Do not use the range function.
makeEvenList(n) 

makeEvenList(2) -> [0, 2]
makeEvenList(5) -> [0, 2, 4, 6, 8]

2. Make a function that returns a list of the hailstone sequence starting with n. This does not have to be recursive. 

makeHailList(n)
makeHailList(3) -> [ 3, 10, 5, 16, 8, 4, 2, 1]
makeHailList(16) -> [16, 8, 4, 2, 1]
Comments