Professional Documents
Culture Documents
def sumlist(lst):
total = 0
for i in lst:
total=total + i
return total
>>>sumlist([1,2,3,4])
10
List Comprehension
One way is a “list comprehension”
[n for n in range(1,5)]
The “if” part of the comprehensive controls which of the iterated values is
collected at the end.
Only those values which make the if part true will be collected:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
Python Dictionary
Use the { } marker to create a dictionary
Use the : marker to indicate key:value pairs:
contacts =
{'bill': '353-1234',
'rich': '269-1234',
'jane': '352-1234'}
Dictionary: Keys and Collections
Key must be immutable:
- strings, integers, tuples are fine
- lists are NOT
Dictionaries are collections,but they are not sequences like
lists, strings or tuples:
- there is no order to the elements of a
dictionary
- in fact, the order might change as elements
are added or deleted.
Access Dictionary Elements
Access requires [ ], but the key is the index!
myDict={}
- an empty dictionary
myDict['bill']=25
- added the pair ‘bill’:25’
print(myDict['bill'])
- prints the value matching to key ‘bill’
myDict['bill'] = 100
- changes the value matching to key ‘bill’
for k in myDict: print(k)
- prints all the keys
for k,v in myDict.items(): print (k,v)
- prints all the key/value pairs
Building Dictionaries Faster
zip creates pairs from two parallel lists:
zip("abc",[1,2,3]) yields
[('a',1),('b',2),('c',3)]
eg.
fib2
eg.
fib
eg.
fib5
(even)
Data Abstractions
●
Abstractions separate implementation of data representation from its
use.
– Functions built on top of points and segments do not access the
underlying tuples directly.
– If implementation changes, those functions do not have to
change
●
Data Abstractions (like procedural abstractions) allow us to build
up complex objects gradually.
ADTs
●
ADT = Abstract Data Type
●
A Methodology for constructing our own compound
data
●
Ingredients:
– Concrete representation for our concept
– Functions to manipulate that representation
ADT Functions: Classification
●
ADT Functions are classified according to their purpose:
●
Constructors: create an instance of our conceptual object
(e.g. makePoint)
●
Selectors: return components of the object e.g. xCoord
●
Predicates: test object for properties, return True/False
●
Mutators: modify an object already in existence
ADT Example:
Binary Tree
Recursive like a list, but with 2 recursive parts:
A binary tree is either
empty OR
a node + 2 binary trees
(Need empty tree to make a non-empty tree)
root
empty
tree left right
subtree subtree
Binary Tree ADT
Constructors:
makeEmptyTree: void → Btree
makeTree: (A, Btree<A>, Btree<A>) → Btree<A>
Selectors:
root: Btree<A> → A
leftSubtree: Btree<A> → Btree<A>
rightSubtree: Btree<A> → Btree<A>
Predicate:
isEmptyTree: Btree<A> → Bool
Binary Tree Contract
isEmptyTree(makeEmptyTree()) → True
5
Binary Tree Example
5
t = makeTree(
5,
makeTree(
7 11 7,
makeEmptyTree(),
makeTree(
13 13,
makeEmptyTree(),
makeEmptyTree()
)
),
makeTree(
11,
makeEmptyTree(),
makeEmptyTree()
)
Binary Tree Example
root (t)
5
Extract 7 from t?
root(leftSubtree(t))
Extract 13 from t?
root(rightSubtree(leftSubtree(t)))
Extract 11 from t?
root(rightSubtree(t))
(FIFO) Queue
FIFO ordering of elements
Used to support:
graph traversal (breadth-first)
game playing (iterated deepening)
event handling
enqueue dequeue
back front
Implementing the Queue ADT:
The Constructors
makeQueue: void → Queue
def makeQueue():
return ('queue', [])
def contents(q):
return q[1]
top
Implementing the Stack ADT:
The Constructor and Predicate
def makeStack():
return ('stack', [])
def contents(s):
return s[1]
●
Good to have a predicate that can detect valid stacks:
def isStack(obj):
return type(obj) == type(()) and \
obj[0] == 'stack'
Implementing the Stack ADT:
The Mutators
push: Stack<A>. <A> → void
def push(s, el):
if isStack(s):
contents(s).insert(0, el)
else:
raise TypeError("push: First arg must be a stack")
pop: Stack<A> → void
def pop(s):
if isStack(s) and not isStackEmpty(s):
contents(s).pop(0)
else:
raise TypeError("pop: arg must be a stack")
Implementing the Stack ADT:
The Selector
top: Stack<A> → <A>
def top(s):
if isStack(s) and not isStackEmpty(s):
return contents(s)[0]
else:
raise TypeError("top: arg must be a stack")
Implementing the Stack ADT:
The Predicate (review)
isStackEmpty: Stack<A> → Bool
def isStackEmpty(s):
if isStack(s):
return contents(s) == []
else:
raise TypeError("isStackEmpty: arg must be a stack")
Procedural Abstraction
1 + 2 + 3 + 4 + 5 = 15
12 + 22 + 32 + 42 = 30
1/12 + 1/32 + 1/52 + ... + 1/1012 ≈ π2/8
1 + 2 + 3 + 4 + 5 = 15
sum(lambda n: n,1,lambda n: n+1,5)
12 + 22 + 32 + 42 = 30
sum(lambda x: x*x, 1, lambda x: x+1, 4)
OR
sum(sqReciprocal, 1, lambda i: i+2, 101)
e.g.
map (lambda n: n**2, [1,2,3,4,5])
map (square, lst)
Generalising: map
Procedure my_map (because map is already a pre-defined function) takes
a function and a list as arguments and produces a list containing the
result of applying that function to each of the elements of the list:
e.g.
my_map(lambda x: x*2, [1,2,3]) => [2, 4, 6]
def list_copy(lst):
return my_map(lambda x: x, lst)
def list_double(lst):
return my_map(lambda x: x*2, lst)
def list_square(lst):
return my_map(lambda x: square(x), lst)
Examples: map
def sq(x): return x * x