Saint Louis University |
Computer Science 150
|
Dept. of Math & Computer Science |
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.
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)
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
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.
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.
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.
Exercise 6.8 of the text.