We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12
Quiz 1 review, part 2
Tuples, Lists, Dictionaries, Assertions,
Recursion Assertions ● Excellent tool for debugging ● Allow you to check that your variables are what you think they should be ● Fail fast
assert <boolean condition>
Tuples ex. months = ('Sept','Oct','Nov','Dec') ● Are like lists, but immutable ● Why are they useful? ○ As keys in dictionaries (lists can’t because they are are mutable) ○ Swapping two variables (x, y = y, x) ○ Returning multiple values from a function List indexing >>> myList = [3,5,2,7] >>> myComplicatedList = [0, [3,4,5], >>> myList[0] [1,2]] 3 >>> myComplicatedList[1] >>> myList[1] = 6 [3, 4, 5] [3, 6, 2, 7] >>> myComplicatedList[1][0] = 9 >>> myList[1:15:2] >>> myComplicatedList[2] = [8,7] [6, 7] [0, [9, 4, 5], [8, 7]] >>> myList[:2] >>> del myComplicatedList[1] [3, 6] [0, [8, 7]] List functions >>> letters = ['a','b','d'] >>> letters.reverse() >>> len(letters) ['e', 'd', 'c', 'b'] 3 >>> letters.pop() >>> letters.append('e') 'b' ['a', 'b', 'd', 'e'] >>> letters >>> letters.insert(2, 'c') ['e', 'd', 'c'] ['a', 'b', 'c', 'd', 'e'] >>> letters.extend(['b', 'a']) >>> letters.remove('a') ['e', 'd', 'c', 'b', 'a'] ['b', 'c', 'd', 'e'] Dictionaries ● Key, value pairs ● Keys can be integers, strings, tuples, etc. (anything immutable) ● Keys can’t be lists, dictionaries, etc. (anything mutable) ● Keys are unique, values don’t have to be Using dictionaries >>> zoo = {'elephant' : 3, 'giraffe' : 4} >>> zoo >>> len(zoo) {'cheetah': 5, 'giraffe': 4, 2 'elephant': 3} >>> zoo['elephant'] >>> zoo.keys() 3 ['cheetah', 'giraffe', 'elephant'] >>> zoo['frog'] >>> zoo.values() KeyError: 'frog' [5, 4, 3] >>> if 'cheetah' not in zoo: >>> del zoo['elephant'] zoo['cheetah'] = 5 >>> zoo {'cheetah': 5, 'giraffe': 4} Mutability Mutable Immutable Lists Strings Dictionaries Tupples Dictionary keys Aliasing ● Two variables are bound to the same object ● Copying (read more about it in the extra notes section of Stellar) ○ Shallow copy ○ copy() ○ deepcopy() Recursion A child couldn't sleep, so her mother told a story about a little frog, who couldn't sleep, so the frog's mother told a story about a little bear, who couldn't sleep, so bear's mother told a story about a little weasel ...who fell asleep. ...and the little bear fell asleep; ...and the little frog fell asleep; ...and the child fell asleep. Recursion ● When a function solves a problem by calling itself on a smaller version of the problem ● Requires 2 things ○ Base case ○ Recursive (inductive) step