anybody familiar with python

all info is in the file with the tester as well. … .
p6.pdf

Unformatted Attachment Preview

Don't use plagiarized sources. Get Your Custom Essay on
anybody familiar with python
Just from $13/Page
Order Essay

CS 112 – Project #6
Due THURSDAY, December 7th, 11:59pm.
Classes and Exceptions
Background:
Classes allow us to define new types for Python. We can first think of a class as defining a new container – instead of a
list, tuple, set, or dictionary, we can have our own collection of values, each with a chosen name rather than an index/key.
We can then read out a value or update a value, much like reading or replacing the values in a list or dictionary. But we
can also put methods in a class definition, giving us a way to specify the exact ways we should interact with values of this
new type. Once we have created a class definition, we can create as many objects of the new type as we want and use
them in our programs. We can create entirely new types during the design phase of writing a program. This enables us to
think in terms of types (and instances of types) that better model what we see in the real world, instead of endlessly
relying on lists or dictionaries (and having to remember exactly how we intended to use those things as proxies for the
values we actually had in mind).
Exceptions allow us to recover from unusual events – some unavoidable (user types in bad file name or bad input in
general), some unexpected (such as IndexErrors when stepping through a list). Without exceptions, we tend to program in
an “ask permission, then attempt” style of calculation. But using exceptions, we can instead program in a “try it first, beg
for forgiveness” approach by writing code that specifies how to recover from exceptions that we allowed to occur.
• Project Basics document:
• Project Six tester file:
http://cs.gmu.edu/~marks/112/projects/project_basics.pdf
http://cs.gmu.edu/~marks/112/projects/tester6p.py
Grading Rubric
There are 105 test cases, each worth one point. There’s no specific function identified as the extra credit.
• if you don’t comment your code or submit it correctly, we might deduct up to 10 points.
• if you use globals, we might deduct up to 10 points.
• if you import unauthorized things, you might lose all points for related test cases.
What’s Allowed?
As long as you don’t import anything, you can use anything built-in or that you create. Now that we’re really
writing our own datatypes, the built-ins aren’t really designed to solve our quite-specific problems! Just as we
used to say “add your own helper functions and call them”, you can also add your own helper methods and use
them.
Task
We will implement some basic classes and method to manage invitations and responses for planning a party. An
Event can add/discard Invitations, and can receive Responses. By calling the methods, someone could managd
their attendees list for their party.
1
Notes / Assumptions / Requirements
•
Don’t import anything, and you can use all built-ins/methods that are otherwise available. J
•
adding definitions: You may add additional methods and functions in support of your solution.
•
displaying things: __str__ and __repr__ are used by many other places in Python to get a string
representation of the object. Specifically, str() calls __str__, and repr() calls __repr__, on any objects
they receive as arguments. __str__ often generates a human-centric representation, appropriate for a human
reading what is present. __repr__ often generates a Python-centric representation. The goal of __repr__ is
actually to have a string that could be evaluated to re-generate an identical object. In general, we would
quite prefer it to look like a valid constructor call, if possible. Ultimately, we can have the same
representation in __str__ and __repr__ if we’d like; in fact, when we didn’t explicitly describe two
different string representations for __str__ and __repr__ to return, we can define one in terms of the
other, like this:
def __repr__(self):
return str(self)
.
Just remember the original intent of __str__ vs __repr__. It’s good practice to define __init__, __str__,
and __repr__ immediately before writing any extra methods in a Python class at a minimum, and perhaps
also __eq__ as well.
•
what to return? Many methods don’t specify a return value, and thus they return None after modifying the
object.
•
handling exceptions: notice where we create exception types, and where we catch those exceptions. Be
sure you don’t catch the exception too early, or when not requested! When testing smaller parts of your code,
it may be possible and even expected/required that specific inputs to a function/method will cause an
exception to propagate (crash), rather than returning normally with a return value. We could extend this
project to a full program with user interactions; this top-level layer of code would be a great place to catch
more exceptions and ask for decisions and responses whenever we catch certain exception types. Since
we’re not writing the larger program that was described, there’s no menu and user interaction present to do
this particular style of interaction.
•
testing individual methods: you can also narrow down the focus of our tester by feeding it the name of a
class (which only runs the init/str/repr/eq/lt kinds of tests), or the method name of things that are
needed in a particular class; this is the Event class. We had to manually create this listing, and it’s how the
test cases were named. Here is the full list of test batches you can select:
o classes: Invitation, Response, InviteNotFoundError, TooManyError, Event
o methods: find_invite, pop_invite, add_invite, find_response, pop_response,
read_response, count_attendees, count_rejections, max_attendance, count_pending,
rescind_invitation
o for example:
demo$ python3 tester6p.py Event Response find_invite pop_invite
2
Required Classes
Working through the classes in the given order is the simplest path to completion. Be sure to complete the
init/str/repr/eq/lt definitions before moving on to other classes that use them.
class Invitation:
• def __init__(self, name, num_invited): create/initialize instance variables for name and
num_invited. Assume num_invited is a positive int.
• def __str__(self): create/return a string as in this example:
“Invitation(‘Alice’,?2)”
• def __repr__(self): create/return a string identical to the __str__ output.
• def __eq__(self, other): determine if this object (self) is equivalent to other. Two Invitations are
•
considered equal if they have the same name and same number of invited people.
def __lt__(self, other): this is the “less than” method. Return the boolean answer of if self num_allowed. Assume both are non-negative ints.
• def __str__(self): create/return a string as in this example: “too?many:?4?requested,?3?allowed.”
• def __repr__(self): create/return a string as in this example:
“TooManyError(5,?3)”
• def __eq__(self, other): determine if this object (self) is equivalent to other (both have same

instance variable values).

3

class Event:
• def __init__(self, title, invites=None, responses=None): create/initialize instance variables for
title, invites, and responses. When invites or responses is None, use an empty list as the value. The

•

•
•

•
•

•

incoming lists of invites and responses might not have been sorted, but must be sorted as part of this
constructor.
def __str__(self): create/return a string similar to: “””Event(‘party’,?[],?[])”””
Hint: when obtaining strings for the lists of invites/responses, how can you rely upon other str definitions to
make this a short/trivial method to write?
def __repr__(self): create/return a string identical to the __str__ output.
def __eq__(self, other): determine if this object (self) is equivalent to other (both have same
instance variable values).
find_invite(self, name): retrieve the Invitation by that name, and return a reference to that Invitation
object. When no such invitation is found, this method will raise an InviteNotFoundError.
pop_invite(self, name): retrieve and remove the invitation by the given name from the list of invites,
and return it. Any Responses of the same name should be discarded. When no such invitation is found, this
method will raise an InviteNotFoundError.
add_invite(self, inv): add this invitation to the event’s list of invites; the list must be sorted before
returning. If there is already an invitation by that name, discard the previous one. Hint: use sort().

•

find_response(self, name): retrieve the Response by that name, and return a reference to that Response
object. When no such response is found, this method will raise a LookupError such as the following:
“no?Response?found?with?name=’Alice’.”
pop_response(self, name): retrieve and remove the response by the given name from the list of
responses, and return it. When no such response is found, it will raise a LookupError as follows:
“no?Response?found?with?name=’Alice’.”
read_response(self, response): check the response, and possibly add it to the list of responses,

•
•
•

count_attendees(self): return how many people are currently attending, according to the responses list.
count_pending(self): return how many inviteds’ invitations have no corresponding response.
max_attendance(self): return the highest number of attendees, if all remaining unanswered invitations

•
•

•

•

according to the following rules:
o If the name wasn’t on the invitation list, raise an InviteNotFoundError out of the method.
o When the response indicates more attending than invited, raise a TooManyError out of the method.
o When the previous two errors are avoided, add response to the list (removing any old ones by that name)
o The responses list must be sorted before returning.
o When the response indicates not attending, replace its num_attending with 0.

responded ‘yes’ with the full number of invited.
count_rejections(self): Count how many responses indicated not coming (how many invited people
are not coming, not just how many rejection responses were received – some are “no” responses, others are
bringing less than invited). All responses should have been validated when added, so if a response has no
associated invitation, behavior is undefined (you don’t have to consider the situation, and whatever your
program does in these situations is acceptable; this is the normal idea of “undefined behavior”, look for it in
specs in the future!).
rescind_invitation(self, name): we’ve decided a person is no longer invited to our party; find and

remove the invitation by that name from this event, as well as any response they may have sent. This
method raises no errors when invitations or responses weren’t found.
Hint: use exception handling to make this a simple function.
4

Example Session
>>> i = Invitation(“Alice”, 2)
>>> i.__str__()
“Invitation(‘Alice’, 2)”
>>> i.__repr__()
“Invitation(‘Alice’, 2)”
>>> i.__eq__(Invitation(“Alice”, 2))
True
>>> i.__lt__(Invitation(“Bob”, 1))
True
>>> i.__lt__(Invitation(“Alice”, 3))
True
>>> i.__lt__(Invitation(“Alex”, 3))
False
>>>
>>> r = Response(“Alice”,True,2)
>>> str(r)
“Response(‘Alice’, True, 2)”
>>> repr(r)
“Response(‘Alice’, True, 2)”
>>> r == Response(“Alice”,True,2)
True
>>> r == Response(“Bob”,True,2)
False
>>> r < Response("Bob",True,2) True >>> r < Response("Alice",False,2) False >>> r < Response("Alice",True,4) True >>>
>>> e = Event(“party”,[Invitation(“Alice”, 2),
Invitation(“Bob”, 2), Invitation(“Alex”, 3)],
[Response(“Alice”,False,0),
Response(“Alex”,True,2)])
>>> e
Event(‘party’, [Invitation(‘Alex’, 3),
Invitation(‘Alice’, 2), Invitation(‘Bob’, 2)],
[Response(‘Alex’, True, 2), Response(‘Alice’, False, 0)])

>>> e.find_invite(“Alice”)
Invitation(‘Alice’, 2)
>>> e.pop_invite(“Alice”)
Invitation(‘Alice’, 2)
>>> e
Event(‘party’, [Invitation(‘Alex’, 3), Invitation(‘Bob’,
2)], [Response(‘Alex’, True, 2)])

>>> e.add_invite(Invitation(“Allen”, 3))
>>> e
Event(‘party’, [Invitation(‘Alex’, 3),
Invitation(‘Allen’, 3), Invitation(‘Bob’, 2)],
[Response(‘Alex’, True, 2)])

>>>
>>> e.find_response(“Alex”)
Response(‘Alex’, True, 2)
>>> e.pop_response(“Alex”)
Response(‘Alex’, True, 2)
>>> e
Event(‘party’, [Invitation(‘Alex’, 3),
Invitation(‘Allen’, 3), Invitation(‘Bob’, 2)], [])

>>>
>>> e.read_response(Response(“Allen”,True,2))
>>> e
Event(‘party’, [Invitation(‘Alex’, 3),
Invitation(‘Allen’, 3), Invitation(‘Bob’, 2)],
[Response(‘Allen’, True, 2)])

>>> e.read_response(Response(“Alex”,False,1))

>>> e
Event(‘party’, [Invitation(‘Alex’, 3),
Invitation(‘Allen’, 3), Invitation(‘Bob’, 2)],
[Response(‘Alex’, False, 0), Response(‘Allen’, True, 2)])

>>>
2
>>>
2
>>>
4
>>>
4
>>>
>>>

e.count_attendees()
e.count_pending()
e.max_attendance()
e.count_rejections()
e.rescind_invitation(“Allen”)
e

Event(‘party’, [Invitation(‘Alex’, 3), Invitation(‘Bob’,
2)], [Response(‘Alex’, False, 0)])

>>>
>>> # exception related
>>> ie = InviteNotFoundError(“Alice”)
>>> str(ie)
“no invite for ‘Alice’ found.”
>>> ie == InviteNotFoundError(“Bob”)
False
>>> raise ie
Traceback (most recent call last):
……
__main__.InviteNotFoundError: no invite for ‘Alice’
found.

>>> te = TooManyError(4,3)
>>> str(te)
‘too many: 4 requested, 3 allowed.’

>>> te == TooManyError(4,3)
True
>>> raise te
Traceback (most recent call last):
……
__main__.TooManyError: too many: 4 requested, 3 allowed.

>>>
>>> e.find_invite(“Patrick”)
Traceback (most recent call last):
……__main__.InviteNotFoundError: no invite for
‘Patrick’ found.

>>> e.pop_invite(“Patrick”)
Traceback (most recent call last):
……__main__.InviteNotFoundError: no invite for
‘Patrick’ found.

>>> e.find_response(“Patrick”)
Traceback (most recent call last):
……
LookupError: no Response found with name=’Patrick’.

>>> e.pop_response(“Patrick”)
Traceback (most recent call last):
……
LookupError: no Response found with name=’Patrick’.

>>> e.read_response(Response(“Patrick”,True,3))
Traceback (most recent call last):
……
__main__.InviteNotFoundError: no invite for ‘Patrick’
found.

>>> e.read_response(Response(“Bob”,True,100))
Traceback (most recent call last):
……
__main__.TooManyError: too many: 100 requested, 2
allowed.

>>> e.rescind_invitation(“Patrick”)
>>> e
Event(‘party’, [Invitation(‘Alex’, 3), Invitation(‘Bob’,
2)], [Response(‘Alex’, False, 0)])


Purchase answer to see full
attachment

Order a unique copy of this paper
(550 words)

Approximate price: $22

Basic features
  • Free title page and bibliography
  • Unlimited revisions
  • Plagiarism-free guarantee
  • Money-back guarantee
  • 24/7 support
On-demand options
  • Writer’s samples
  • Part-by-part delivery
  • Overnight delivery
  • Copies of used sources
  • Expert Proofreading
Paper format
  • 275 words per page
  • 12 pt Arial/Times New Roman
  • Double line spacing
  • Any citation style (APA, MLA, Chicago/Turabian, Harvard)

Our guarantees

Delivering a high-quality product at a reasonable price is not enough anymore.
That’s why we have developed 5 beneficial guarantees that will make your experience with our service enjoyable, easy, and safe.

Money-back guarantee

You have to be 100% sure of the quality of your product to give a money-back guarantee. This describes us perfectly. Make sure that this guarantee is totally transparent.

Read more

Zero-plagiarism guarantee

Each paper is composed from scratch, according to your instructions. It is then checked by our plagiarism-detection software. There is no gap where plagiarism could squeeze in.

Read more

Free-revision policy

Thanks to our free revisions, there is no way for you to be unsatisfied. We will work on your paper until you are completely happy with the result.

Read more

Privacy policy

Your email is safe, as we store it according to international data protection rules. Your bank details are secure, as we use only reliable payment systems.

Read more

Fair-cooperation guarantee

By sending us your money, you buy the service we provide. Check out our terms and conditions if you prefer business talks to be laid out in official language.

Read more

Calculate the price of your order

550 words
We'll send you the first draft for approval by September 11, 2018 at 10:52 AM
Total price:
$26
The price is based on these factors:
Academic level
Number of pages
Urgency

Order your essay today and save 15% with the discount code ESSAYHELP