Sale!

Lab # 10 ITI 1120 Objects solved

Original price was: $35.00.Current price is: $30.00. $25.50

Category:

Description

5/5 - (6 votes)

Starting Lab 10
• Open a browser and log into Brightspace
• On the left hand side under Labs tab, find lab 10 material contained
in lab10-students.zip file
• Download that file to the Desktop and unzip it.
Most of the programming exercises in this lab are from your textbook:
LjubomirPerkovic. Introduction to Computing Using Python: An
Application Development Focus, 2nd Edition
2
Before starting, always make sure
you are running Python 3
This slide is applicable to all labs, exercises, assignments … etc
ALWAYS MAKE SURE FIRST that you are running Python 3.
That is, when you click on IDLE (or start python any other way)
look at the first line that the Python shell displays. It should say
Python 3.
If you do not know how to do this, read the material provided
with Lab 1. It explains it step by step
3
4
Later on if you wish, you can type them
into a computer (or copy/paste from the
solutions once I poste them)
Do all the exercises labeled as
Task in your head i.e. on a
paper
Task 1: “Reference” Variables and Objects
(a) What does the program below print? (Class Point is a simplified version of the
class we designed in class). IMPORTANT: notice that the function riddle is outside
of Point class (pay attention to what is lined up)
(b) http://www.pythontutor.com/visualize.html#mode
Open file t1.py and copy it in Python Vizualizer. Make sure you understand what is
happening with variables as you step through the execution of the program.
Task 2: “Reference” Variables and Objects
(a) What does the program below print? (Class Point is a simplified version of the
class we designed in class)
(b) http://www.pythontutor.com/visualize.html#mode
Open file t2.py and copy it in Python Vizualizer. Make sure you understand what is
happening with variables as you step through the execution of the program.
Task 3: “Reference” Variables and Objects
(a) What does the program on the left
prints? The objects you design are
MUTABLE.
(b) Open file t3.py and copy it in Python
Vizualizer. Make sure you understand
what is happening with variables as
you step through the execution of the
program.
Task 4: “Reference” Variables and Objects
(a) What does the program on the left
prints?
(b) Open file t3.py and copy it in Python
Vizualizer. Make sure you understand
what is happening with variables as
you step through the execution of the
program.
A class method is really a function defined in the
class namespace; when Python executes
it first translates it to
and actually executes this last statement
Introduction to Computing Using Python
Class methods (REVIEW) >>> lst = [9, 1, 8, 2, 7, 3]
>>> lst
[9, 1, 8, 2, 7, 3]
>>> lst.sort()
>>> lst
[1, 2, 3, 7, 8, 9]
>>>
__add__
list
__add__() sort()
count x
count()
pop
pop()
. . .
>>> lst = [9, 1, 8, 2, 7, 3]
>>> lst
[9, 1, 8, 2, 7, 3]
>>> lst.sort()
>>> lst
[1, 2, 3, 7, 8, 9]
>>> lst = [9, 1, 8, 2, 7, 3]
>>> lst
[9, 1, 8, 2, 7, 3]
>>> list.sort(lst)
>>> lst
[1, 2, 3, 7, 8, 9]
>>>
>>> lst = [9, 1, 8, 2, 7, 3]
>>> lst
[9, 1, 8, 2, 7, 3]
>>> lst.sort()
>>> lst
[1, 2, 3, 7, 8, 9]
>>> lst = [9, 1, 8, 2, 7, 3]
>>> lst
[9, 1, 8, 2, 7, 3]
>>> list.sort(lst)
>>> lst
[1, 2, 3, 7, 8, 9]
>>> lst.append(6)
>>> lst
[1, 2, 3, 7, 8, 9, 6]
>>>
>>> lst = [9, 1, 8, 2, 7, 3]
>>> lst
[9, 1, 8, 2, 7, 3]
>>> lst.sort()
>>> lst
[1, 2, 3, 7, 8, 9]
>>> lst = [9, 1, 8, 2, 7, 3]
>>> lst
[9, 1, 8, 2, 7, 3]
>>> list.sort(lst)
>>> lst
[1, 2, 3, 7, 8, 9]
>>> lst.append(6)
>>> lst
[1, 2, 3, 7, 8, 9, 6]
>>> list.append(lst, 5)
>>> lst
[1, 2, 3, 7, 8, 9, 6, 5]
lst.sort()
list.sort(lst)
lst.append(6) instance.method(arg1, arg2, …)
list.append(lst, 6) class.method(self, arg1, arg2, …)
The function has
an extra argument,
which is the object
invoking the method
Task 5: Methods class translation to
Function calls
– Open the file called t5.py and translate all the indicated
method calls to equivalent function calls
– Once done run those function calls in Python shell to
observe that they indeed are equivalent to their method
call couterparts
Programming exercise 1:
Open file lab10.py It contains the classes we developed during lectures last week. Do the
following exercises:
A) Add method distance to the class Point. It takes another Point object as input and returns
the distance to that point (from the point invoking the method). (Recall that you need to import
math to get sqrt function)
>>> c = Point(0,1)
>>> d = Point(1,0)
>>> c.distance(d)
1.4142135623730951
B) Add to class Point methods up, down, left, and right that move the Point object by 1
unit in the appropriate direction. The implementation of each should not modify instance
variables x and y directly but rather indirectly by calling existing method move().
>>> a = Point(3, 4)
>>> a.left()
>>> a.get()
(2, 4)
C) In to class Animal modify the constructor to set age of the Animal object. Also add method
getAge to retrieve the age of the Animal object.
>>> flipper = Animal(‘dolphin’, ‘?’, 3)
>>> flipper.getAge()
3
Operator Method
x + y x.__add__(y)
x – y x.__sub__(y)
x * y x.__mul__(y)
x / y x.__truediv__(y)
x // y x.__floordiv__(y)
x % y x.__mod__(y)
x == y x.__eq__(y)
x != y x.__ne__(y)
x > y x.__gt__(y)
x >= y x.__ge__(y)
x < y x.__lt__(y)
x <= y x.__le__(y)
repr(x) x.__repr__()
str(x) x.__str__()
len(x) x.__len__()
(x) .__init__(x)
Introduction to Computing Using Python
Python operators
In Python, all expressions involving
operators are translated into method calls
>>> ‘!’*10
‘!!!!!!!!!!’
>>> [1,2,3] == [2,3,4]
False
>>> 2 < 5 True >>> ‘a’ <= ‘a’ True >>> len([1,1,2,3,5,8])
6
>>> repr([1,2,3])
‘[1, 2, 3]’
>>> repr(193)
‘193’
>>> repr(set())
‘set()’
Built-in function repr()returns the
canonical string representation of an object
>>> [1,2,3]
[1, 2, 3]
>>> 193
193
>>> set()
set()
>>> [1,2,3].__repr__()
‘[1, 2, 3]’
>>> int(193).__repr__()
‘193’
>>> set().__repr__()
‘set()’
• This is the representation printed by
the shell when evaluating the object
>> ‘!’.__mul__(10)
‘!!!!!!!!!!’
>>> [1,2,3].__eq__([2,3,4])
False
>>> int(2).__lt__(5)
True
>>> ‘a’.__le__(‘a’)
True
>>> [1,1,2,3,5,8].__len__()
6
>>> a = Point(3, 4)
>>> a
Point(3, 4)
Introduction to Computing Using Python
Overloading repr()
In Python, operators are translated into method calls
To add an overloaded operator to a user-defined class, the
corresponding method must be implemented
>>> a = Point(3, 4)
>>> a
Point(3, 4)
To get this behavior
method __repr__()must be implemented and added to class Point
class Point:
# other Point methods here
def __repr__(self):
‘canonical string representation Point(x, y)’
return ‘Point({}, {})’.format(self.x, self.y)
__repr__() should return the (canonical) string representation of the point
>>> a = Point(3, 4)
>>> a.__repr__()
Point(3, 4)
Introduction to Computing Using Python
Overloading operator +
To get this behavior
method __add__()must be implemented and added to class Point
class Point:
# other Point methods here
def __add__(self, point):
return Point(self.x+point.x, self.y+point.y)
def __repr__(self):
‘canonical string representation Point(x, y)’
return ‘Point({}, {})’.format(self.x, self.y)
>>> a = Point(3,4)
>>> b = Point(1,2)
>>> a+b
Point(4, 6)
__add__()should return a new Point object whose coordinates are the
sum of the coordinates of a and b
>>> a = Point(3,4)
>>> b = Point(1,2)
>>> a.__add__(b)
Point(4, 6)
Also, method __repr__() should be implemented to achieve the desired
display of the result in the shell
>>> a = Point(3,4)
>>> b = Point(1,2)
>>> a+b
Point(4, 6)
>>> a = Point(3,4)
>>> b = Point(1,2)
>>> a.__add__(b)
Point(4, 6)
>>> print([1,2,3])
[1, 2, 3]
>>> print(193)
193
>>> print(set())
set()
>>> [1,2,3].__str__()
‘[1, 2, 3]’
>>> int(193).__str__()
‘193’
>>> set().__str__()
‘set()’
Operator Method
x + y x.__add__(y)
x – y x.__sub__(y)
x * y x.__mul__(y)
x / y x.__truediv__(y)
x // y x.__floordiv__(y)
x % y x.__mod__(y)
x == y x.__eq__(y)
x != y x.__ne__(y)
x > y x.__gt__(y)
x >= y x.__ge__(y)
x < y x.__lt__(y)
x <= y x.__le__(y)
repr(x) x.__repr__()
str(x) x.__str__()
len(x) x.__len__()
(x) .__init__(x)
Introduction to Computing Using Python
str() vs repr()
>>> str([1,2,3])
‘[1, 2, 3]’
>>> str(193)
‘193’
>>> str(set())
‘set()’
Built-in function __str()__ returns the
“pretty” string representation of an object
• This is the representation printed by
the print() statement and is meant
to be readable by humans
Built-in function __repr()__ returns the
canonical string representation of an object
• This is the representation printed by
the shell when evaluating the object
• The string returned by __repr__
method must look like the statement
that creates that object
Programming exercise 2:
Open file lab10.py. It contains the classes we developed during lectures last week. Do
the following exercises:
Overload appropriate operators for class Card so that you can compare cards based on
rank. In particular override __gt__ , __ge__ , __lt__ and __le__
>>> c1=Card(‘3′,’\u2660’)
>>> c2=Card(‘5′,’\u2662’)
>>> c1
Card(3,♠)
>>> c2
Card(5,♢)
>>> c1 < c2 True >>> c1 > c2
False
>>> c1<=c2 True Programming exercise 3: Bank Account Develop a class BankAccountthat supports these methods: •__init__:Initializes the bank account balance to the value of the input argument, or to 0 if no input argument is given • withdraw: Takes an amount as input and withdraws it from the balance • deposit: Takes an amount as input and adds it to the balance • balance: Returns the balance on the account •__repr__: >>> x = BankAccount(700)
>>> x.balance()
700.0
>>> x.withdraw(70)
>>> x.balance()
630.0
>>> x.deposit(7)
>>> x.balance()
637.0
>>> x
BankAccount(637.0)
Programming exercise 4: Ping Pong
Write a class named PingPong that has a method nextthat alternates
between printing ‘PING’ and ‘PONG’ as shown below.
>>> ball = PingPong()
>>> ball.next()
PING
>>> ball.next()
PONG
>>> ball.next()
PING
>>> ball.next()
PONG
Programming exercise 5a: Class Queue
Goal: develop a class Queue , an ordered collection of objects that restricts
insertions to the rear of the queue and removal from the front of the queue
•The class Queue should support methods:
• Queue(): Constructor that initializes the queue to an empty queue
• enqueue(item): Add item to the end of the queue
• dequeue(): Remove and return the element at the front of the
queue
• isEmpty(): Returns True if the queue is empty, False otherwise
>>> appts = Queue()
>>> appts.enqueue(‘John’)
>>> appts.enqueue(‘Annie’)
>>> appts.enqueue(‘Sandy’)
>>> appts.dequeue()
‘John’
>>> appts.dequeue()
‘Annie’
>>> appts.dequeue()
‘Sandy’
>>> appts.isEmpty()
True
rear rear
‘Annie’ ‘Sandy’
Introduction to Computing Using Python by Lj. Perkovic
Class Queue: example
>>> appts = Queue()
>>> appts.enqueue(‘John’)
>>> appts.enqueue(‘Annie’)
>>> appts.enqueue(‘Sandy’)
>>> appts.dequeue()
‘John’
>>>
>>> appts = Queue()
>>> appts.enqueue(‘John’)
>>> appts.enqueue(‘Annie’)
>>> appts.enqueue(‘Sandy’)
>>> appts.dequeue()
‘John’
>>> appts.dequeue()
‘Annie’
>>>
>>> appts = Queue()
>>> appts.enqueue(‘John’)
>>> appts.enqueue(‘Annie’)
>>> appts.enqueue(‘Sandy’)
>>> appts.dequeue()
‘John’
>>> appts.dequeue()
‘Annie’
>>> appts.dequeue()
‘Sandy’
>>>
>>> appts = Queue()
>>> appts.enqueue(‘John’)
>>> appts.enqueue(‘Annie’)
>>> appts.enqueue(‘Sandy’)
>>> appts.dequeue()
‘John’
>>> appts.dequeue()
‘Annie’
>>> appts.dequeue()
‘Sandy’
>>> appts.isEmpty()
True
appts ‘John’
front
rear
‘Annie’ ‘Sandy’
rear rear
Programming exercise 5b: Class Queue
Make your class Queue user friendly by adding to it __eq__,
__repr__ and __len__
Example:
>>> q1=Queue()
>>> q1.enqueue(‘kiwi’)
>>> q1.enqueue(‘apple’)
>>> print(q1)
>>> print(q1)
Queue([‘kiwi’, ‘apple’])
>>> len(q1)
2
>>> q2=Queue()
>>> q2.enqueue(‘apple’)
>>> q1==q2
False
>>> q1.dequeue()
‘kiwi’
>>> q1==q2
True
Programming exercise (Inheritance) 6:
Class Vector
Implement a class Vector that supports the same methods as the class Point we
developed in class. In other words it inherits all atributes (data and methods) from class
Point. (Revisit class Animal and Bird to see a simple example)
The class Vector should also support vector addition and product operations.
The addition of two vectors
>>> v1 = Vector(1, 3)
>>> v2 = Vector(-2, 4)
is a new vector whose coordinates are the sum of the corresponding coordinates of v1
and v2:
>>> v1 + v2
Vector(-1, 7)
The product of v1 and v2 is the sum of the products of the corresponding coordinates:
>>> v1 * v2
10
In order for a Vector object to be displayed as Vector(., .) instead of Point(.,
.),you will need to override method __repr__().
Programming exercise 7a: Class Marsupial
Write a class named Marsupialthat can be used as shown below:
>>> m=Marsupial(“red”)
>>> m.put_in_pouch(‘doll’)
>>> m.put_in_pouch(‘firetruck’)
>>> m.put_in_pouch(‘kitten’)
>>> m.pouch_contents()
[‘doll’, ‘firetruck’, ‘kitten’]
>>> print(m)
I am a red Marsupial.
Programming exercise 7b (Inheritance):
Class Kangaroo
Write a class named Kangaroo as a
subclass of Marsupialthat inherits all
the attributes of Marsupial and also:
•extends the Marsupial
__init__ constructor to take, as
input, the coordinates x and y of the
Kangaroo object,
•has methodjump that takes number
values dx and dy as input and moves the
kangaroo by dx units along the x-axis
and by dy units along the y-axis, and
•overloads the __str__ operator so it
behaves as shown below.
>>> k = Kangaroo(“blue”, 0,0)
>>> print(k)
I am a blue Kangaroo located
at coordinates (0,0)
>>> k.put_in_pouch(‘doll’)
>>>
k.put_in_pouch(‘firetruck’)
>>> k.put_in_pouch(‘kitten’)
>>> k.pouch_contents()
[‘doll’, ‘firetruck’,
‘kitten’]
>>> k.jump(1,0)
>>> k.jump(1,0)
>>> k.jump(1,0)
>>> print(k)
I am a blue Kangaroo located
at coordinates (3,0)
Programming exercise 8 : Class Points
Write a class named Points(that represents points in the plane). The class has a list
containing elements that are objects of type Point.
__init__ constructor creates an empty list if no input list is given. Otherwise it
sets the list to the given list.
•has method add(x,y) that adds an object Point with coordinates x and y to
points
•has method left_most_point that returns the left most point in the set. If
there is more than one left most it returns the bottom left most
•Has method len and overrides __repr__
>>> a=[Point(1,1), Point(1,2), Point(2,20), Point(1.5, -20)]
>>> mypoints=Points(a)
>>> mypoints.add(1,-1)
>>> mypoints.left_most_point()
Point(1,-1)
>>> len(mypoints)
5
>>> mypoints
Points([Point(1,1), Point(1,2), Point(2,20), Point(1.5,-20),Point(1,-1)])