11. Exercises

  1. Add a distance_from_point method that works similar to distance_from_origin except that it takes a Point as a parameter and computes the distance between that point and self.

  2. Add a method reflect_x to the class Point which returns a new Point, one which is the reflection of the point across the x-axis. For example, Point(3, 5).reflect_x() is (3, -5)

  3. Add a method slope_from_origin, which returns the slope of the line joining the origin to the point. For example,

    >>> Point(4, 10).slope_from_origin()
    2.5
    >>> Point(12, -3).slope_from_origin()
    -0.25
    >>> Point(-6, 0).slope_from_origin()
    0
    

    The equation for calculating slope between any two points is slope = (Y2 - Y1) / (X2 - X1). Remember that dividing by 0 is not allowed, so there are some inputs that will cause your method to fail. Return None when that happens.

  4. Add a method called move that will take two parameters, call them dx and dy. The method will cause the point to move in the x and y direction the number of units given. (Hint: you will change the values of the state of the point)

Graded Lesson Assignment

Create a Car class that has the following characteristics:

  • It has a gas_level attribute.
  • It has a constructor (__init__ method) that takes a float representing the initial gas level and sets the gas level of the car to this value.
  • It has an add_gas method that takes a single float value and adds this amount to the current value of the gas_level attribute.
  • It has a fill_up method that sets the car’s gas level up to 13.0 by adding the amount of gas necessary to reach this level. It will return a float of the amount of gas that had to be added to the car to get the gas level up to 13.0. However, if the car’s gas level was greater than or equal to 13.0 to begin with, then it doesn’t need to add anything and it simply returns a 0.

(Note: you can call the add_gas method from within the fill_up method by using this syntax: self.add_gas(amount).)

Here’s an example.

example_car = Car(9)
print(example_car.fill_up())  # should print 4

another_car = Car(18)
print(another_car.fill_up()) # should print 0

Reminder: Don’t forget about the self parameter!

Ready to submit your code? Time to fork, and submit a Pull Request to: this Github Repository.