Download presentation
Presentation is loading. Please wait.
1
Intro to Programming Lecture 5
CIT 590 Intro to Programming Lecture 5
2
One more unit testing example
Let’s write a unit test for something in HW3 checkRacko(hand) – remember this returns True or False Assume also some added specification – throw errors if the rack being passed in does not have 10 cards the rack has cards that are not in [1,60]
3
Dictionary Dictionaries consist of key, value pairs
Also know as Hashmaps, associative arrays in other languages Initialized with dictionary = {} And then we can add key, value pairs as follows dictionary[‘name’] = ‘Arvind’ dictionary[‘age’] = 92 Very efficient way of storing sparse data A lot of matrices and vectors that come up in probability are sparse, so you could use an integer key and store values in that manner
4
Dictionary update operation. Copying dictionaries
Dictone = {‘abc’: 3, ‘def’:7, ‘xyz’: 9} Dicttwo = {‘def’: 5, ‘pdq’ : 4} Dictone.update(dicttwo) As with lists or for that matter any kind of assignment, you need to be careful when you do assignment, since that is done by reference So dict1 = dict2 will make both dictionaries refer to the same value If you want to make what is generally called a ‘shallow copy’, you need to use the copy method Dict 2 = dict1.copy()
5
Altering dictionaries by passing them into functions
Remember that arguments are passed into functions by reference, so you could get some unintended consequences if you are not careful
6
Initializing a dictionary version 2
The dict() function can convert a list of 2 element tuples into dictionaries Very useful when you want to initialize a dictionary by using 2 lists, one of which has keys = [‘Arvind’, ‘Aashish’] values = [33, 28] dict(zip(keys, values))
7
Looping over a dictionary
For e in dict: This will loop over the keys For e in dict.values(): As is somewhat obvious, this will loop over the values Since there is no guarantee about what order the keys are looped over, you might sometimes want to call the sorted function
8
Fibonacci sequence The naïve recursive version is just
Fib(n) = Fib(n-1) + Fib(n-2) Why does this take so long??
9
Dynamic programming The central principle is that you delay the computation of the function as much as possible When you compute a result, store it somewhere in memory Retrieve the results from memory
10
Persistent variables The shelve module allows data to persist without using explicit file commands import shelve Data = shelve.open(“database”) #and this will make an implicit file called database And then data from that point can basically be treated just as any other dictionary Remember to close the shelf before quitting by using Data.close()
11
The internal dictionaries
Locals() gives you the local variables Correspondingly global() gives you the global variables
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.