On 25/10/13 09:13, Amir Fawzi wrote:

Exercise 7.4. Make a class for straight lines.
Make a class Line whose constructor takes two points p1 and p2 (2-
tuples or 2-lists) as input. The line goes through these two points (see
function line in Chapter 3.1.7 for the relevant formula of the line).

I don;t have the reference but assume it is one of the standard math equations like y=mx+c?

So for your class you need to work out m and c and in your value() function apply them to the input x to return y.

The trick is that you need to solve the simultaneous equations at p1 and p2 for y=mx+c. I assume you know how to do that in math and then translate that into Python?

If not come back with more specific questions.

 >>> from Line import Line
 >>> line = Line((0,-1), (2,4))
 >>> print line.value(0.5), line.value(0), line.value(1)
0.25 -1.0 1.5

My answer:

class Line:
     def __init__(self, p1, p2):
         self.p1 = p1
         self.p2 = p2

     def value(self, x):
     p1 = (y1 - y0)/float(x1 -x0)   # Formula referred to in chapter
3.1.7 in the book
         p2 = (y0 - a*x0)                   # return <value of the line
at point x>

I'm guessing that last one should be

p2 = y0 - p1*x0 ?

But you want to calculate this in the init method and store them
as attributes of the line. It might be nice to give them meaniungful names like gradient and, erm, const?

Then your y value is just a case of multiplying x by the gradient(p1) and adding the const(p2).

def line (x0, y0, x1, y1):
     p1 = (x0 - x1)
     p2 = (y0 - y1)
     return p1, p2

I'm not sure what this is supposed to be?

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to