Course Home | Assignments | Computing Resources | Lab Hours/Tutoring | Python | Schedule | Submit

Saint Louis University

Computer Science 150
Introduction to Object-Oriented Programming

Michael Goldwasser

Spring 2013

Dept. of Math & Computer Science

Homework Assignment 06

Class Definitions

Contents:


Overview

Topic: Class Definitions
Related Reading: Chapter 6
Due: 1:10pm, Friday, 22 March 2013

Please make sure you adhere to the policies on academic integrity.


Problems to be Submitted (20 points)

  1. (5 points)

    Exercise 6.2 of the text.
    For full credit, you must explain the reason for each error and how it could be corrected.

    (electronic version of that code, in case you want to see the interpreter's error messages)

  2. (5 points)

    Exercise 6.4 of the text.
    For full credit, you must explain why the output appears as such!
    (electronic version of that code, in case you want to execute it)

For the next two questions, we consider the following motiviation. In class and in the text, we describe a robust verison of a Point class that is used to represent two-dimensional points. If we wanted to represent three-dimensional, we could rewrite that code presumably to include a z-coordinate. But that seems like a poor design to have to duplicate so much code for a closely related concept. Worse yet, what if we wanted a four-dimensional point? or a five-dimensional point?

A better approach is to design a single Point class that can be used to model a point with arbitrary dimension. We've started such a class (code here). Internally, we keep a list of coordinates. For uniformity, rather than identifying coordinates with letters like x and y, we use indexing so that the coordinates of a point p can be referenced using a syntax such as p[k] for the kth coordinate (when zero-indexed). We do that by implementing special methods __getitem__ and __setitem__ in lieu of the methods getX, setX getY, and setY from our original Point class definition.

In fact, we can generalize all of the behaviors originally shown in the two-dimensional case. For our new multi-dimensional Point class, we have intentionally omitted implementations for two methods: scale and sum. Your goal is to implement those.

  1. (5 points)

    Give a legitimate implementation for the scale method, so that a syntax such as p.scale(3) mutates the state of Point p so that all coordinates are multiplied by the given factor.

  2. (5 points)

    Give a legitimate implementation for the __add__ method, so that a syntax such as p + q returns a new Point instance representing the coordinate-wise sum of the original two. You may assume that the syntax will only be invoked upon Points with equal dimension.


Extra Credit

  1. (2 points)

    Exercise 6.8 of the text.


Michael Goldwasser
CSCI 150, Spring 2013
Last modified: Sunday, 20 March 2011
Course Home | Assignments | Computing Resources | Lab Hours/Tutoring | Python | Schedule | Submit