Download Inf2a: Lab 2 (Solutions)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Inf2a: Lab 2 (Solutions)
Introduction to Python - Part 2
Paolo Besana, Laura Hutchins-Korte and Bonnie Webber
Week 3:
1
59 October 2009
More on Object Oriented Programming
Exercise 1
Using your preferred editor, create a class that checks if a string (infix) is
contained in other strings. The class must be initialised passing the
infix
string, that must be stored in a class variable. The class must expose the
method
check(string)
that veries if
in
string1 in string2).
string (you can use the operator
another one:
infix
is contained in the passed
to verify if a string is contained in
Remember to use self when trying to access to class methods and attributes.
Import your module into the python shell, and test its behaviour (you
must instantiate the class passing the inx string, and then call the method
check passing dierent strings)
If you use the statement import modulename , remember to use the modulename
prex in front of the class name. If you make an error in the class, and you need
to reimport the module, use reload(modulename): import will not reimport a
module already imported. You will also have to reinstantiate the class.
Solution:
class Checker:
def __init__(self,infix):
self.infix = infix
def check(self, str):
return self.infix in str
2
2.1
More on Data Types
Lists
Exercise 2
1
Using your preferred editor, create a class named
Queue
that models a
queue: the rst element that enters is the rst that exits (FIFO: First In,
First Out). The class will use a list to maintain the data. It will expose
the following methods:
. isempty():
veries if the queue is empty
. push(item)
inserts an element at the end of the queue
. pop()
: extracts and returns the rst element in the queue (possibly
only if the queue is not empty)
Import the module into the python shell, and test it
Remember to create the list that contains the data before accessing to it.
Solution
class Queue:
def __init__(self):
self.q = []
def isempty(self):
return len(self.q)==0
def push(self,item):
self.q.append(item)
def pop(self):
if not self.isempty():
return self.q.pop(0)
Exercise 3
Using your preferred editor, create a class named
Stack
that models a
stack: the last element that enters is the rst that exits (LIFO: Last in,
First Out). The class willl use a list to maintain the data. It will expose
the following methods:
. isempty():
veries if the stack is empty
. push(item):
. pop():
inserts an element at the end of the stack
extracts and returns the last element of the stack (possibly
only if the stack is not empty)
Import the module into the python shell, and test it
Remember to create the list that contains the data before accessing to it.
2
Solution
class Stack:
def __init__(self):
self.s = []
def isempty(self):
return len(self.s)==0
def push(self,item):
self.s.append(item)
def pop(self):
if not self.isempty():
return self.s.pop()
2.2
Dictionaries
Exercise 4
Create a class for managing an phone book. The user must be able to:
.
insert a name and their phone number,
.
obtain a number when given a name,
.
verify if name is in the phone book,
.
list all the names and phone numbers in the phone book,
.
delete a name from the phone book
.
as
optional feature,
the user should be able to print in alphabetical
order the names and their phone numbers
Import your class into the python shell, and test it. (Remember to instantiate the class.)
Use a dictionary to store the data, and remember to create the dictionary before
using it. You can use the method keys() to obtain the list of all keys. Then
you can apply any method available for lists on the list you have obtained.
3
Solution
class AddressBook:
def __init__(self):
self.b = {}
def insert(self,name, phone):
self.b[name]=phone
def get(self,name):
return self.b[name]
def has_name(self,name):
return self.b.has_key(name)
def list(self):
for n,p in self.b.iteritems():
print n,p
def delete(self, name):
del self.b[name]
def orderedList(self):
orderedkeys = self.b.keys()
orderedkeys.sort()
for n in orderedkeys:
print n, self.b[n]
3
Pattern matching
Exercise 5
Create a regular expression that checks if a string starts with 3 binary
010asda must be recognised, while 1aa must be rejected.
re.match("[0|1][0|1][0|1][a-z|0-9]*", "010adsa")
digits. Test it:
Since in Python regular expressions | is just syntactic sugar for OR and since
Python allows the {n} operator to mean n copies of the previous expression,
a shorter version of the above would be:
re.match("[01]{3}[a-z0-9]*", "010asda")
Using a regular expression, write a python statement that nds all the
words that end with ly in strings. Test it using, for example, the string
it is likely to happen rarely.
re.findall("[\w]+ly","it is likely to happen rarely")
Using a regular expression, write a python statement that replaces all the
words that start with wh with WH-word. Test it using, for example, the
who should do what?.
re.sub("wh\w+","WH-word","who should do what?")
string
4