Logo
  • Home
  • Classes
  • Conveying Computing
  • Exams
  • Fractal Gallery
  • Guides
  • Problem Sets
  • Syllabus

PS6 Comments

Question 1: For each Scheme fragment below, write an analogous Python fragment. Evaluating your expression in the Python Shell should produce the results shown. For the last part, note that unlike in Scheme where the interpreter ignores whitespace, indentation matters in Python!

  1. (+ 1 1)

    2

    1 + 1
  2. (+ (* 2 3) (* 4 5))

    26

       (2 * 3) + (4 * 5)
    
    Note that parentheses are optional, but not necessary here, since the * operator has higher precedence (will bind its operands earlier) than the + operator, so the Python expression 2*3+4*5 means what we think it should mathematically.
  3. (define (square x) (* x x))
      def square(x): return x*x
    
  4. (square 4)

    16

       square(4)
    
  5. (if (> 3 4) 5 6)

    6

    if 3 > 4:
       5
    else:
       6
    

Question 2: By examining the code in adventure.py and understanding what it means to inherit methods in subclasses, explain what happens when:

  1. The is_ownable method is invoked on a OwnableObject.
    The OwnableObject class defines a method,
        def is_ownable(self): return True
    
    so when is_ownable() is invoked on an OwnableObject, the result is True.
  2. The is_ownable method is invoked on a MobileObject.
    The MobileObject class does not define an is_ownable method, so when is_ownable() is invoked on a MobileObject, the superclass method is called. The superclass of MobileObject is PhysicalObject. The PhysicalObject class also does not define the is_ownable method, so we look to its superclass, SimObject. This implements the method,
        def is_ownable(self):
            return False # overridden by some subtypes
    
    so the result of is_ownable() when invoked on a MobileObject is False.
Question 3: A Professor is even more arrogant than a Lecturer. Define a Professor class that is a subclass of Lecturer. Define a method profess in your Professor class that is like lecturing in that every comment ends in "you should be taking notes", but precedes every statement with "It is intuitively obvious that". (Your Professor class definition should not be more than about 3 lines long and should take advantage of work already done in the Lecturer superclass.)
class Professor (Lecturer):
	def profess(self, s):
	    self.lecture("It is intuitively obvious that " + s)
Note that this is better than using,
        self.say("It is intuitively obvious that " + s + " - you should be taking notes")
since it avoids the duplication from the lecture method.
Question 4: A Dean is like a Professor, but follows every statement with a request for donations. Define a Dean class that is a subclass of Professor. Your Dean class should override the say method so that after every utterance it makes a request for money. (Your Dean class definition should not be more than about 3 lines long.) [Syntax hint: to access the superclass say method, use Professor.say(self, stuff).]
class Dean (Professor):
   def say(self, s):
       Professor.say(self, s + " Please give money, we are in debt!")
Question 5: A Student is a special kind of Person (this doesn't necessarily mean all students are special or kind, just that they are all persons). Define a Student class that is a subtype of Person.

Some of the students in Charlottansville have a strange habit of getting undressed and running around the Green, so the Student class needs an instance variable dressed that indicates whether or not the student is clothed. Initially, all students are dressed, so the dressed variable is initialized to True. So, your Student class needs to override the __init__ constructor, similarly to how the Person class overrides the __init__ constructor of MobileObject.

In addition, your Student class should implement three methods:

  • get_undressed(self) — If the object is already undressed, it should say something about having no more clothes to remove. Otherwise, change the state of dressed to False. (In Scheme, we would name this method get-undressed! with an exclamation point to indicate that the method is a mutator since it changes the state of the self object. Python does not allow ! to be used in names, so we cannot include one in the method name, event though depending on the current location of the student, it may be appropriate to have more than one exclamation point here.) The undressed student should also say "Brr! It's cold!" (or something more creative, but not less tasteful).
  • get_dressed(self) — changes the state of dressed to True. If the student was undressed, the student should say "I feel much better now.".
  • is_dressed(self) — evaluates to True if the student is dressed and False otherwise.
class Student(Person):
    def __init__(self, name):
        Person.__init__(self, name)
        self.dressed = True

    def get_undressed(self):
        if is_dressed():
            self.dressed = False
            self.say("Brr! It's cold!")
        else:
            self.say("I have nothing left to remove!")

    def get_dressed(self):
        if !is_dressed:
            self.say("I feel much better now.")
            self.dressed = True
        else:
            self.say("I'm already dressed, thank you.");

    def is_dressed(self):
        return self.dressed
Question 6: Define a method in your PoliceOfficer class that makes an arrest. Your method should be called arrest and take a Person as its parameter (in addition to the self parameter).
    def arrest(self, person):
        if self.location != person.location:
            self.say("I cannot arrest " + person.name + " because she is at " + person.location.name)
        else:
            self.say(person.name + ", you are under arrest!)
            self.say("You have the right to remain silent, call methods, and mutate state.")
            person.move(self._jail)
Question 7: Define a tick method for your PoliceOfficer class. The tick method should automatically arrest everyone streaking in the same place as the police officer. (That is, any Student objects that are not dressed should be arrested.) If no one is streaking in the officer's location, the police officer should act like a normal person — that is, it should then invoke the superclass (Person) tick() method. [Hint: you can use isinstance(t, Student) to determine if t is a Student object.] The police officer should not invoke the superclass tick() method if someone is streaking in the officer's location.
There are many different ways to define tick. One way is to loop through all the things at the current location to check if any are undressed students (this is based on Anthony Teate's submission):
    def tick(self):
        foundAny = False
        for p in self.location.get_things():
            if isinstance(p, Student):
                if not p.is_dressed():
                    foundAny = True
                    self.arrest(p)
        if not foundAny:
            self.say("No one to arrest here")
            Person.tick(self)
Another strategy is to use filter, which is built-in to Python and similar to the list-filter method from the book, and map, which is similar to list-map. This is based on Anjali Nanda and Harry Peppiatt's solution:
    def tick(self):
        students = filter(lambda s: isinstance(s, Student), self.location.get_things())
        undressedstudents = filter(lambda t: t.is_dressed() == False, students)
        if len(undressedstudents) == 0:
            self.say("Its lonely here...")
            Person.tick(self)
        else:
            map(lambda undressedstudent: self.arrest(undressedstudent), undressedstudents)
We could make this shorter by combining both tests into a single filter:
    def tick(self):
        streakers = filter(lambda s: isinstance(s, Student) and s.is_dressed(), 
                    	   self.location.get_things())
        if len(streakers) == 0:
            self.say("Its lonely here...")
            Person.tick(self)
        else:
            map(lambda s: self.arrest(s), streakers)
Question 8: Design a non-trivial extension to this simulated world. Use your imagination!
Many interesting extensions were submitted, but I'm happy to report that Charlotansville has been saved (at least for now) from the Zombies, Ghosts, SlackerProfessor, Rhino, and Rabbits by Confusious, CarMan, and the Firefighter.
Print Friendly Print Get a PDF version of this webpage PDF

Leave a Reply Cancel reply

You must be logged in to post a comment.

cs1120 | RSS | Comments RSS | Book | Using These Materials | Login | Admin | Powered by Wordpress