0% found this document useful (0 votes)
13 views36 pages

Lecture 34

The document discusses Python concepts like isinstance(), private methods, iterators, and more data structures like tuples, sets, and dictionaries. It provides code examples and explanations of these concepts.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
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
0% found this document useful (0 votes)
13 views36 pages

Lecture 34

The document discusses Python concepts like isinstance(), private methods, iterators, and more data structures like tuples, sets, and dictionaries. It provides code examples and explanations of these concepts.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
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/ 36

Computer Science 1001

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.

• The syntax of this function is


isinstance(object,class)

• This function can be useful when we create classes,


to ensure that the appropriate type is passed into a
constructor.

• For example, in our Rational class, we would


expect integer values for the numerator and
denominator.

• We can ensure that attempts to construct Rational


numbers with non-integer values fail by raising a
TypeError.

• We can then catch that TypeError and ask the


user to re-enter values to construct a Rational
number.

– 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

• We have seen how to make attributes and methods


private in Python.

• In the above example we have made the


setRational() method private.

• In Python, prepending __ to make an attribute or


method private results in name mangling.

• All attributes and methods with __ prepended


have their names changed by adding the name
of the class. For example __name is changed to
_classname__name.

• We could actually use this name to access a


“private” attribute or method outside of the class,
but we shouldn’t!

– CS1001 Lecture 34 – 4
Private methods

• Consider the following code:

class Person:
def __getInfo(self):
return "Person"

def printPerson(self):
print(self.__getInfo())

class Student(Person):
def __getInfo(self):
return "Student"

Student().printPerson()

• Here, Student() produces an instance of the


Student class, which has a private method named
__getInfo().

• We know that private methods are not inherited,


so the __getInfo() methods of the Person and
Student classes are distinct methods.

– CS1001 Lecture 34 – 5
Private methods
• Calling the printPerson() method on a
Student() will execute the method inherited from
Person.

• Within that method there is a call to


self.__getInfo(). The __getInfo() method
within Person had its name mangled to be
_Person__getInfo(). This is therefore the version
that is called from within the printPerson()
method of the Person class.

• So, although we are calling this method on an


object of type Student, the _Person__getInfo()
method is executed.

• In the case where the getInfo() methods are


not “private”, their names are not mangled.
A getInfo() method in Student would thus
override the same method in Person and would
be executed when an instance of Student called
printPerson().

– CS1001 Lecture 34 – 6
Iterators

• We have seen how sequence types in python can be


iterated over using a for loop.

• We may want to add this functionality to our own


classes.

• When a for loop is executed, a function called


iter() is called which returns an iterator object.

• An iterator object defines a method called


__next__() which accesses elements one at a time.
When there are no more elements a StopIteration
exception is raised.

• There is a built-in Python function called next()


which accepts an iterator argument to return the
next element.

• To make our own classes iterable, we define an


__iter__() method which returns an object that
contains a __next__() method.

– CS1001 Lecture 34 – 7
Iterators

• If we define __next__() within our class, then


__iter__() can simply return self.

• If we consider our Stack class, we would want to


iterate over the elements in reverse order (last-in-
first-out). This could be implemented as follows:

class Stack:
def __init__(self):
self.__elements = []

# return True if stack is empty


def isEmpty(self):
return len(self.__elements)==0

# returns the element at the top of the stack


# without removing it from the stack
def peek(self):
if self.isEmpty():
return None
else:
return self.__elements[len(self.__elements)-1]

# add element to the top of the stack


def push(self,value):
self.__elements.append(value)

– 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()

# return the size of the stack


def getSize(self):
return len(self.__elements)

# convert the elements in the stack to a string


# elements are separated by spaces
def __str__(self):
return " ".join([str(x) for x in self.__elements])

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

• A data structure is a particular way of storing and


organizing data so that it can be used efficiently.

• The best data structure to use for a particular


application or algorithm depends on how the data
is represented and how it needs to be used.

• Suppose we would like to store:


– values associated with keys;
– elements meant to be constant throughout a
program;
– or elements with unique values.

• In Python, we could use a list for each of these


cases.

• However, there is a specific data structure that is


more appropriate and/or efficient for each of these
tasks.

– CS1001 Lecture 34 – 12
More data structures

• To store elements meant to be constant


(immutable) throughout a program we can use a
tuple.

• To store unique values we can use a set.

• To store values associated with keys we could use a


dict (dictionary).

– CS1001 Lecture 34 – 13
Tuples

• Tuples are like lists but their elements are fixed


(immutable).

• Tuples are sequences and hence can be traversed


using a for loop.

• Once a tuple is created, its elements cannot be


changed.
– One cannot add, delete, replace or reorder the
elements in a tuple.

• If the contents of a list are not supposed to


change, you should use a tuple to prevent accidental
changes.
– For example, to store the months of the year, the
days of the week, etc.

– CS1001 Lecture 34 – 14
Tuples

• A tuple is created by enclosing its elements inside a


pair of parentheses or using the tuple constructor.

• Elements are separated by commas.

• For example,

>>> t=() # create an empty tuple


>>> type(t)
<class ’tuple’>
>>> t1=(3,) # create a tuple with one element. Note the comma.
>>> t2=(1,3,5) # create a tuple with three elements
>>> t2
(1, 3, 5)
>>> t3=tuple([2*x for x in range(1,5)])
>>> t3
(2, 4, 6, 8)
>>> t4=tuple("abc")
>>> t4
(’a’, ’b’, ’c’)
>>> lst = list(t4) # create a list from a tuple
>>> lst
[’a’, ’b’, ’c’]

– CS1001 Lecture 34 – 15
Functions for tuples

• The following functions can be used with tuple


arguments:
Function Description
len(t) returns the number of elements in tuple t
max(t) returns the largest element in tuple t
min(t) returns the smallest element in t
sum(t) returns the sum of all numbers in tuple t

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

• The following operators can be used with tuple


operands:
Operator Description
+ concatenates two tuples
*n concatenates n copies of a tuple
in returns True if an element is in the tuple
not in returns True if an element is not in the tuple

• The comparison operators (==, <=, etc.) can also


be used on 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

• An individual element of a tuple can be accessed


using the index operator [ ], as in

>>> t=(1,4,2)
>>> t[1]
4

• A subset of a tuple can be accessed using the slicing


operator, as in

>>> t=(3,2,5,1,7,5,8)
>>> t[2:5]
(5, 1, 7)

– CS1001 Lecture 34 – 18
Sets

• A set is an unordered collection with no duplicate


elements.

• If a collection of elements does not require any


particular order and duplicates should not be
permitted, then using a set to store the collection is
more efficient that using a list.

• Sets support mathematical operations such as


union, intersection, difference and symmetric
difference.

– CS1001 Lecture 34 – 19
Sets

• Sets are created by enclosing the elements inside a


pair of curly braces { } or using the set constructor.

• Elements are separated by commas.

• For example,

>>> s1=set() # create an empty set. Don’t use s1={}


>>> s2={1,3,5} # create a set with three elements
>>> s3=set((2,4,6)) # create a set from a tuple
>>> s4 = set([x*2 for x in range(1,5)]) # create a set from a list
>>> s4
{8, 2, 4, 6}
>>> s5 = set("abca") # create a set from a string
>>> s5
{’c’, ’a’, ’b’}

– CS1001 Lecture 34 – 20
Functions for sets

• The following functions can be used with set


arguments:
Function Description
len(s) returns the number of elements in set s
max(s) returns the largest element in set s
min(s) returns the smallest element in set s
sum(s) returns the sum of all numbers in set s

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

• The following operators can be used with set


operands:
Operator Description
in returns True if an element is in the set
not in returns True if an element is not in the set
== returns True if two sets contain the same elements
!= returns True if two sets contain different elements

For example,
>>> s1={"x","y","z"}
>>> s2={"a","b","c"}
>>> s1==s2
False
>>> "a" not in s2
False
>>> "y" in s1
True

• Note that you cannot use the index operator or the


slicing operator to access elements in a set because
the elements are not in any particular order.

– 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

• The set class also has methods to compare the


contents of a set with another set:
Operator Description
issubset(s) returns True if every element of the set is in s
issuperset(s) returns True if every element of s is in the set
isdisjoint(s) returns True if s is disjoint from the set (their
intersection is the empty set)

• The comparison operators can also be used similarly:


– The <= operator is the same as issubset.
– The >= operator is the same as issuperset.
– The < operator returns True if the set is a proper
subset of another.
– The > operator returns True if the set is a proper
superset of another.

• A set s1 is a proper subset of a set s2 if every


element in s1 is also in s2, and at least one element
in s2 is not in s1. Similarly for proper superset.

– 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

• The set class contains methods to compare


sets using the mathematical set operations union,
intersection, difference, and symmetric difference.

• 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).

• intersection(s) (same as &)


s1.intersection(s2) returns a sets that is the
intersection of s1 and s2 (ie. a set that contains
the elements common to both sets).

• 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.

• In Python, a dictionary is an object of the class


dict.

• The keys are like an index operator and must be


unique; each key maps to one value.

• A dictionary enables fast retrieval, deletion and


updating of the value by using the key.

keys values

dictionary entry

– CS1001 Lecture 34 – 28
Dictionary example

• Suppose you need to write a program that stores


information for a million students and frequently
searches for a student using the student number.

• One can use a dictionary to store the information


for each student and retrieve it using the student
number.

– CS1001 Lecture 34 – 29
Creating a dictionary

• A dictionary is created by enclosing the items inside


a pair of curly braces { }.

• Items are separated by commas.

• Each item consists of a key, followed by a colon,


followed by a value.

• The key must be a hashable type such as numbers


and strings.

• The value can be of any type.

• For example,

>>> dictionary = {} # create an empty dictionary


>>> dictionary = {"john":40,"peter":45}
>>> dictionary
{’peter’: 45, ’john’: 40}
>>> type(dictionary)
<class ’dict’>

– CS1001 Lecture 34 – 30
Adding, modifying and retrieving
dictionary values

• To add an entry to a dictionary, use:

dictionaryName[key] = value

For example,

students["2015041678"] = ’Susan’

If the key is already in the dictionary, the previous


statement replaces the value for that key.

• To retrieve a value, write an expression using:

dictionaryName[key]

If the key is in the dictionary, the value for the key


is returned. Otherwise, an error occurs.

– CS1001 Lecture 34 – 31
Deleting items from a dictionary

• To delete an entry from a dictionary, use:

del dictionary[key]

For example,

del students["2015041678"]

• This deletes an item with the key 2015041678 from


the dictionary.

• If the key is not in the dictionary, an error occurs.

– 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

Note that you cannot use the comparison operators <,


<=, >, or >= on dictionaries since the items are not
ordered.

– 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.

str1 = input("Please enter a sentence: ")


str1 = str1.lower()

lst = list(str1) # convert to list of characters


dictionary = {} # create empty dictionary

# store characters as keys in dictionary with


# count of characters as dictionary values
for c in lst:
if c in dictionary:
dictionary[c] += 1
else:
dictionary[c] = 1

# Sort keys alphabetically


keys = sorted(dictionary)

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

You might also like