本帖最后由 drongh 于 2012-04-08 10:30 编辑
Write a function slope(x1, y1, x2, y2) that returns the slope of the line through the points (x1, y1) and (x2, y2). Be sure your implementation of slope can pass the following doctests:
def slope(x1, y1, x2, y2):
"""
>>> slope(5, 3, 4, 2)
1.0
>>> slope(1, 2, 3, 2)
0.0
>>> slope(1, 2, 3, 3)
0.5
>>> slope(2, 4, 1, 2)
2.0
"""
Then a call to slope in a new function named intercept(x1, y1, x2, y2) that returns the y-intercept of the line through the points (x1, y1) and (x2, y2).
def intercept(x1, y1, x2, y2):
"""
>>> intercept(1, 6, 3, 12)
3.0
>>> intercept(6, 1, 1, 6)
7.0
>>> intercept(4, 6, 12, 
5.0
"""
intercept should pass the doctests above.
后面的半个怎么做。
下面是前半个题目的程序,已经完成。
def slope(x1,y1,x2,y2):
"""
>>> slope(5,3,4,2)
1.0
>>> slope(1,2,3,2)
0.0
>>> slope(1,2,3,3)
0.5
>>> slope(2,4,1,2)
2.0
"""
if x1 == x2:
print "The slope doesn't exist"
return
else:
return (float(y2-y1)) / (x2-x1)
if __name__ == '__main__':
import doctest
doctest.testmod()
|