Question

So having some trouble with a class methods. I'll post all the information that I have. I need to write the relevant methods for the questions given.

import math
epsilon = 0.000001
class Point(object):
    def __init__(self, x, y):
        self._x = x
        self._y = y

    def __repr__(self):
        return "Point({0}, {1})".format(self._x, self._y)

First question; i need to add a method, called disttopoint that takes another point object, p, as an argument and returns the euclidean distance between the two points. I can use math.sqrt.

test cases:

abc = Point(1,2)
efg = Point(3,4)
abc.disttopoint(efg) ===> 2.8284271

Second question; add a method, called isnear that takes another point object, p, as an argument and returns True if the distance between this point and p is less than epsilon (defined in the class skeleton above) and False otherwise. Use disttopoint.

test cases:

abc = Point(1,2)
efg = Point(1.00000000001, 2.0000000001)
abc.isnear(efg) ===> True

Third question; add a method called addpoint that takes another point object p as an arguement and changes this point so that it is the sum of the oint's old value and the value of p.

test cases;

abc = Point(1,2)
efg = Point(3,4)
abc.add_point(bar)
repr(abc) ==> "Point(4,6)
Was it helpful?

Solution

class Point(object):
    # __init__ and __repr__ methods
    # ...
    def disttopoint(self, other):
        # do something using self and other to calculate distance to point
        # result = distance to point
        return result

    def isnear(self, other):
        if (self.disttopoint(other) < epsilon):
            return True
        return False

OTHER TIPS

What is your issue here ?

are you stuck with creating methods ?

Class Point(object):
  # make it part of the class as it will be used in it
  # and not in the module
  epsilon = 0.000001

  def __init__(self, x, y):
      self._x = x
      self._y = y

  def __repr__(self):
      return "Point({0}, {1})".format(self._x, self._y)

  def add_point(self, point):
      """ Sum the point values to the instance. """
      self._x += point._x
      self._y += point._y

  def dist_to_point(self, point):
      """ returns the euclidean distance between the instance and the point."""
      return math.sqrt(blablab)

  def is_near(self, point):
      """ returns True if the distance between this point and p is less than epsilon."""
      return self.dist_to_point(point) < self.epsilon

does that help you ?

Jordi

def dist_to_point(self, point):
      """ returns the euclidean distance between the instance and the point."""
      return math.sqrt(res)

What should the variable "res" contain?

Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top