Description
for problem 2 turn the problem 13-14 file into a py. Please do the same for the testif file I’ve uploaded. To be clear turn it from pdf to py for those two named files
Unformatted Attachment Preview
Python Programming
Homework 3
Instructor: Dr. Ionut Cardei
The following problems are from Chapters 11 (Intro to Classes), 12 (More on Classes), and 13
(Programming with Classes).
For full credit:
make sure you follow exactly all requirements listed in this document,
the code must be easily readable, have all required features and run as expected.
write a docstring for each method that describes the method’s contract (preconditions,
postconditions, parameters, as needed).
follow the coding style taught in the book. Check out the Google Python Style Guide.
upload on Canvas: the PDF file with all solutions plus the .py source files, in this order.
First, write the solution to a problem i in in a Pyhton file pi.py, for i=1…n.
Then, paste your answers into a new Word document called h3.doc. When done, convert it to PDF and
upload the PDF version (h3.pdf) and the solution .py files on Canvas.
The PDF file is very important: the instructor will write comments on top of the PDF file on Canvas for
you to read and learn from your mistakes.
Write your full name at the top of the file and add a heading before each problem solution.
List the solutions in the PDF file in the given order, 1, 2,.…
Syntax highlighting for the code pasted in the Word file makes it more readable and helps avoid
grading mistakes. Pasting from Spyder (or another IDE) into Word may preserve the Python
colors and styles. If not, consider using http://hilite.me/ or some other online service.
The problems are missing some details (e.g. on design, some method names). Where
unspecified by requirements, feel free to make your own decisions on design and
implementation as long as they comply with the book material, coding style, and don’t
contradict the requirements. If in doubt, ask on the Homework Q&A Forum, or ask the
instructor by email.
You have unlimited attempts to upload this assignment, but only the last one before the deadline
will be graded.
IMPORTANT:
Your solution must be your own original work and it must NOT include code that was shared or
copied from somewhere else. Doing otherwise is against the FAU Code of Academic Integrity.
For this assignment the instructor will use a cheating detector application that finds submissions that
indicate code shared or copied.
Name each required .py file like this: px_Lastname_Firstname.py, Substitute x with the problem
number, and Lastname, Firstname with your own last name and first name.
Example: if the problem number is 2 and your name is Jane Austen, name the problem 2 source file
p2_Austen_Jane.py.
NOTE: In the following problems the double-quote characters “ and ” may be used for examples.
Replace with ” when typing or trying the examples.
Problem 1 (60 points).
Write the code for this problem in a file named p1_Lastname_Firstname.py, as required above.
a) Implement in Python a class for a mutable string called Mstring.
Class Mstring must have the following interface:
– a constructor that takes any object as argument and constructs a mutable string object
– method __len__ with their standard role; returns int
– methods __str__, __repr__ with their standard role; must return str
– methods __add__ and __radd__ for concatenating two Mstring objects or an Mstring with a str; must
return Mstring
– method __getitem__ that works like str.__getitem__; must work also with a negative index; must
return str
– method __setitem__ that sets a character at a given index; must work also with a negative index;
throws IndexError if the index is invalid
– methods __eq__, __ne__ that compare an Mstring with another Mstring, or with a str.
– method replace(s, t) that replaces the first occurrence of a substring s with another string t; it returns
the index of the substring s if s was found, or -1 otherwise
– method find that works like str.find
Make sure your methods throw the same type of exception as equivalent methods in the str class (as
applicable).
Examples:
ms1 = Mstring(“Hello World”)
print(ms1) # prints: Hello World
print(ms1[3])
# prints: l
print(ms1[-3])
# prints: r
print(ms1[20])
# throws IndexError
print(len(ms1)) # prints 11
ms2 = Mstring(“abcdef”)
print(ms2 + “ xyz”)
Mstring
# addition with regular string: prints abcdef xyz. Caution: + must return
print(“0123” + ms2 )
Mstring
# addition with regular string: prints 0123abcdef. Caution: + must return
print(ms2 + Mstring(“1234””))
# prints abcded1234. Caution: + must return Mstring
ms2[2] = “X”
print(ms2) # prints abXdef
ms2[7] = “Y” throws index error
ms2[-7] = “Y” throws index error
ms2[3] = “ZZ” throws ValueError since we can’t insert a multi-character string with []=
Mstring(“abcd”) == Mstring(“abcd”) should return true
Mstring(“abcd”) == Mstring(“abcX”) should return false
ms3 = Mstring(“01234567”)
print(ms3.find(“45”) ) # prints 4
print(ms3.find(“abc”) ) # prints -1
print(ms3.replace(“34”, “XYZABC”))
# prints 3
print(ms3)
# prints 012XYZABC567
ms4 = Mstring(“01234567”)
print(ms4.replace(“AB”, “XYZ”))
print(ms4) # prints 01234567
# prints -1
Important implementation details:
Avoid re-computing a str value unless the underlying characters have changed. Use caching.
Pick an internal representation for the characters that is efficient when using __setitem__ and
__getitem__.
b) Write a function called unit_tests that uses the testif() function (at the end of this file) with unit tests
for the following Mstring methods: __eq__, __ne__, __str__, __len__, __add__, __radd__,
__setitem__, __getitem__, replace
Make sure you include success and failure cases. Test also with the empty string object Mstring(“”).
Add a print statement for each test explaining what is tested.
c) Write a function (not a method!) called quicksort that sorts in place the characters in an Mstring
object and that relies on Mstring’s [] operators to read and write characters. Use the classical quicksort
algorithm, of courses.
d) Write a function test_sort that tests the function from part c) on some representative strings,
including the empty Mstring.
e) write a function called main that runs unit_tests and test_sort.
Answer this question in the PDF file: how does your choice of representation for the mutable string
data impact the performance of the quicksort function?
Take a screenshot with the output of your program.
Problem 2 (40 points).
Write the code for this problem in a file named p3_Lastname_Firstname.py, as required above.
Take the prey-predator problem described in Chapter 13 and add humans. Start from file program1314.py, attached to the assignment page.
A human is an animal that kills and eats only prey, and also moves and breeds like an animal. Humans
do not kill predators.
Here are the detailed rules pertaining to humans:
A Human object moves like an Animal object on the island grid.
A Human object does not kill predators.
A Human object eats Prey objects periodically. Every Human.hunt_time clock ticks (starting with
the Human object’s creation time), if a Prey is in a neighboring cell (using check_grid()), the
Human will move to its cell and remove the Prey from the island, in the same way as Predators eat
Prey objects.
A Human object “starves” and is removed from the island if it has not killed a Prey within a
starving time given by a Human.starve_time class attribute, initialized in main().
A Human object breeds like an Animal object, with the breeding period given by a
Human.breed_time class attribute, initialized in main().
All other rules for Prey and Predators remain in effect.
We want to study the impact of humans on the island animal populations. Add the following to the
Island class:
Proper initialization for Human objects. The constructor and init_animals() should take each an
extra parameter count_humans and init_animals() should position Human objects at random
positions.
A method count_humans() that returns the number of Human objects on the grid.
The main() method should:
Take extra parameters for the Human class attributes described above and should properly
initialize them.
Keep track of the Human population for each clock tick in the same ways it’s done for Predator
and Prey objects.
Stop the simulation after 1000 time units.
Display at the end with matplotlib the evolution in time of the Prey, Predator, and Human
populations.
Display the island grid to the terminal, at the beginning and at the end of the simulation.
More requirements:
1. Add a Human class to the existing class hierarchy so that code is properly reused. Use the
problem description above to decide what class is Human’s superclass.
2. Use the object-oriented design process. Integrate class Human smoothly into the existing design
and code.
3. Print a Human object on the Island grid with character ‘H’.
4. Apply the proper coding style and techniques taught in this class.
5. Run the program with different combinations of parameters and find an interesting case.
6. Take a screenshot with the matplotlib chart showing the evolution of the three populations vs.
time. Insert this screenshot in the Word document. This chart looks like that on slide 46 in the
Chapter 13 lecture notes PDF flle.
7. Take a screenshot with the terminal showing the island grid printout (first tick and last tick) +
any other statistics displayed in main(). Insert this screenshot in the Word document.
IMPORTANT NOTES:
A submission that does not follow the instructions 100% (i.e. perfectly) will not get full credit.
Did you include all the required screenshots
Upload the PDF file and .py source files on Canvas, in this order.
Only submissions uploaded before the deadline will be graded.
You have unlimited attempts to upload this assignment, but only the last one uploaded before
the deadline will be graded.
Rubric (100 points maximum):
Points for each problem are assigned as follows:
code correctness and screenshots (if required): 85%
coding style and following standards: 15%
APPENDIX A
The testif function used for writing unit tests:
Purchase answer to see full
attachment