Lecture 34
Lecture 34
Lecture 34
Lecture Outline
• Additional topics
– CS1001 Lecture 34 –
isinstance
• Python provides a function called isinstance()
to determine whether an object is an instance of a
particular class.
– CS1001 Lecture 34 – 1
isinstance
class Rational:
def __init__(self, numerator=0, denominator=1):
self.__setRational(numerator,denominator)
def __setRational(self,numerator,denominator):
if not isinstance(numerator,int):
raise TypeError("Numerator must be an integer.")
if not isinstance(denominator,int):
raise TypeError("Denominator must be an integer.")
divisor = gcd(numerator, denominator)
self.__numerator = (1 if denominator > 0 else -1) \
* int(numerator/divisor)
self.__denominator = int(abs(denominator)/divisor)
...
def main():
while True:
n1,d1 = eval(input("Enter numerator, denominator: "))
n2,d2 = eval(input("Enter numerator, denominator: "))
try:
r1=Rational(n1,d1)
r2=Rational(n2,d2)
print("r1+r2=",r1+r2)
break
except TypeError as ex:
print("TypeError",ex)
print("Enter another value")
if __name__=="__main__":
main()
– CS1001 Lecture 34 – 2
isinstance
Sample input/output:
Enter numerator, denominator: 2.5,3
Enter numerator, denominator: 4,5
TypeError Numerator must be an integer.
Enter another value
Enter numerator, denominator: 3,’a’
Enter numerator, denominator: 2,3
TypeError Denominator must be an integer.
Enter another value
Enter numerator, denominator: 1,3
Enter numerator, denominator: 2,4
r1+r2= 5/6
– CS1001 Lecture 34 – 3
Private methods
– CS1001 Lecture 34 – 4
Private methods
class Person:
def __getInfo(self):
return "Person"
def printPerson(self):
print(self.__getInfo())
class Student(Person):
def __getInfo(self):
return "Student"
Student().printPerson()
– CS1001 Lecture 34 – 5
Private methods
• Calling the printPerson() method on a
Student() will execute the method inherited from
Person.
– CS1001 Lecture 34 – 6
Iterators
– CS1001 Lecture 34 – 7
Iterators
class Stack:
def __init__(self):
self.__elements = []
– CS1001 Lecture 34 – 8
# remove element at the top of the stack and return it
def pop(self):
if self.isEmpty():
return None
else:
return self.__elements.pop()
def __iter__(self):
self.__num=len(self.__elements)
return self
def __next__(self):
if self.__num==0:
raise StopIteration
self.__num-=1
return self.__elements[self.__num]
– CS1001 Lecture 34 – 9
Iterators
from stack import Stack
stack = Stack()
for i in range(10):
stack.push(i)
print("Stack: ",stack)
print("Pop value",stack.pop())
print("Stack: ",stack)
print("Peek value: ",stack.peek())
print("Stack: ",stack)
print("Loop over values in stack:")
for x in stack:
print(x)
Output:
Stack: 0 1 2 3 4 5 6 7 8 9
Pop value 9
Stack: 0 1 2 3 4 5 6 7 8
Peek value: 8
Stack: 0 1 2 3 4 5 6 7 8
Loop over values in stack:
8
7
6
5
4
3
2
1
0
– CS1001 Lecture 34 – 10
Iterators
Using the built-in iter and next functions:
>>> from stack import Stack
>>> s = Stack()
>>> for i in range(5):
... s.push(i)
...
>>> s
<stack.Stack object at 0x7fbd3a8f5588>
>>> print(s)
0 1 2 3 4
>>> it = iter(s)
>>> type(it)
<class ’stack.Stack’>
>>> next(it)
4
>>> next(it)
3
>>> next(it)
2
>>> next(it)
1
>>> next(it)
0
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "stack.py", line 43, in __next__
raise StopIteration
StopIteration
– CS1001 Lecture 34 – 11
More data structures
– CS1001 Lecture 34 – 12
More data structures
– CS1001 Lecture 34 – 13
Tuples
– CS1001 Lecture 34 – 14
Tuples
• For example,
– CS1001 Lecture 34 – 15
Functions for tuples
For example,
>>> t = (8,3,2,5)
>>> len(t)
4
>>> max(t)
8
>>> min(t)
2
>>> sum(t)
18
– CS1001 Lecture 34 – 16
Operators for tuples
For example,
>>> t1=(1,3,5)
>>> t2=(1,2,4)
>>> t3=t1+t2
>>> t3
(1, 3, 5, 1, 2, 4)
>>> t1*2
(1, 3, 5, 1, 3, 5)
>>> 3 in t1
True
>>> t1==t2
False
– CS1001 Lecture 34 – 17
Accessing elements of a tuple
>>> t=(1,4,2)
>>> t[1]
4
>>> t=(3,2,5,1,7,5,8)
>>> t[2:5]
(5, 1, 7)
– CS1001 Lecture 34 – 18
Sets
– CS1001 Lecture 34 – 19
Sets
• For example,
– CS1001 Lecture 34 – 20
Functions for sets
For example,
>>> s1={"x","y","z"}
>>> len(s1)
3
>>> max(s1)
’z’
>>> min(s1)
’x’
>>> s2={6,3,10}
>>> sum(s2)
19
– CS1001 Lecture 34 – 21
Operators for sets
For example,
>>> s1={"x","y","z"}
>>> s2={"a","b","c"}
>>> s1==s2
False
>>> "a" not in s2
False
>>> "y" in s1
True
– CS1001 Lecture 34 – 22
Set methods
• The set class has several methods available:
Operator Description
add(x) add element x to the set
remove(x) remove x from the set (error if x is not in the set)
discard(x) remove x from the set if it is present
pop() remove and return an arbitrary element from the set
(error if the set is empty)
clear() remove all elements from the set
For example,
>>> s={2,3,4}
>>> s.add(5)
>>> s
{2, 3, 4, 5}
>>> s.remove(2)
>>> s
{3, 4, 5}
>>> s.discard(5)
>>> s
{3, 4}
>>> s.add(7)
>>> s.pop()
3
>>> s
{4, 7}
>>> s.clear()
>>> s
set()
– CS1001 Lecture 34 – 23
Set methods
– CS1001 Lecture 34 – 24
• For example,
>>> s1={1,2,4}
>>> s2={1,4,5,2,6}
>>> s1.issubset(s2)
True
>>> s1 <= s2 # same as s1.issubset(s2)
True
>>> s1 < s2
True
>>> s2.issuperset(s1)
True
>>> s1 >= s2 # same as s1.issuperset(s2)
False
>>> s2 > s1
True
>>> s1==s2
False
>>> s1.isdisjoint(s2)
False
>>> s1.isdisjoint({3,7})
True
>>> s3={3,5,7}
– CS1001 Lecture 34 – 25
Set methods
• union(s) (same as |)
s1.union(s2) returns a set that is the union of s1
and s2 (ie. a set that contains all elements from
both s1 and s2).
• difference(s) (same as -)
s1.difference(s2) returns a set that contains
the elements that are in s1 but not in s2.
• symmetric_difference(s) (same as ^)
s1.symmetric_difference(s2) returns a set that
– CS1001 Lecture 34 – 26
contains the elements that are in either s1 or s2,
but not in both (exclusive or).
• For example,
>>> s2.union(s3)
{1, 2, 3, 4, 5, 6, 7}
>>> s2 | s3 # same as union()
{1, 2, 3, 4, 5, 6, 7}
>>> s4={1,2,5}
>>> s1
{1, 2, 4}
>>> s1.intersection(s4)
{1, 2}
>>> s1 & s4 # same as s1.intersection(s4)
{1, 2}
>>> s1.difference(s4)
{4}
>>> s1 - s4 # same as s1.difference(s4)
{4}
>>> s4 - s1 # same as s4.difference(s1)
{5}
>>> s3.symmetric_difference(s4)
{1, 2, 3, 7}
>>> s3 ^ s4 # same as s3.symmetric_difference(s4)
{1, 2, 3, 7}
– CS1001 Lecture 34 – 27
Dictionaries
• A dictionary is an efficient data structure to store a
collection of key/value pairs.
keys values
dictionary entry
– CS1001 Lecture 34 – 28
Dictionary example
– CS1001 Lecture 34 – 29
Creating a dictionary
• For example,
– CS1001 Lecture 34 – 30
Adding, modifying and retrieving
dictionary values
dictionaryName[key] = value
For example,
students["2015041678"] = ’Susan’
dictionaryName[key]
– CS1001 Lecture 34 – 31
Deleting items from a dictionary
del dictionary[key]
For example,
del students["2015041678"]
– CS1001 Lecture 34 – 32
Dictionary functions, methods, &
operators
Function Description
len(d) returns the number of items in dictionary d
in returns True if a key is in the dictionary
not in returns True if a key is not in the dictionary
== returns True if two dictionaries contain the same
items
!= returns True if two dictionaries do not contain the
same items
get(key) returns the value for the key (or None if the key is not
in the dictionary)
pop(key) removes key and returns its value. If key is not in the
dictionary, an error occurs
popitem() remove and return an arbitrary (key,value) pair (as a
tuple) from the dictionary
clear() delete all items in the dictionary
values() returns a sequence of all values in the dictionary
keys() returns a sequence of all keys in the dictionary
items() returns a sequence of all the dictionary’s items, as
(key,value) pairs
– CS1001 Lecture 34 – 33
Example: counting symbols
We will now write a Python program that asks the
user to enter a sentence, counts the occurrences of
each character that appears in the sentence using a
dictionary, and outputs the characters, in alphabetical
order, along with their number of occurrences.
# Count the number of occurrences of each character in a
# user-input sentence.
for i in keys:
print(i, " occurs ", dictionary[i], " times.")
– CS1001 Lecture 34 – 34
Example: sample input/output
Please enter a sentence: The quick brown fox jumps over the lazy dog.
occurs 8 times.
. occurs 1 times.
a occurs 1 times.
b occurs 1 times.
c occurs 1 times.
d occurs 2 times.
e occurs 4 times.
f occurs 1 times.
g occurs 1 times.
h occurs 2 times.
i occurs 1 times.
j occurs 1 times.
k occurs 1 times.
l occurs 1 times.
m occurs 1 times.
n occurs 1 times.
o occurs 4 times.
p occurs 1 times.
q occurs 1 times.
r occurs 2 times.
t occurs 2 times.
u occurs 2 times.
v occurs 1 times.
w occurs 1 times.
x occurs 1 times.
y occurs 1 times.
z occurs 1 times.
– CS1001 Lecture 34 – 35