In: Computer Science
Write a python function that will return the total length of line that passes through any number of provided points ( (x,y) ). The points should be passed as individual tuples or lists. The function should also have a parameter (True or False) to indicate whether the line should start from the origin, and that parameter should default to False. If True, the returned value should include the distance from the origin to the first point, otherwise start adding distances from the first point. So a function call could look something like this:
dist = lineLength((1,2), (2,3), (7,4), start=False)
Demonstrate it in your main program by calculating the length of
line going through the following 5 points (with and without the
origin option set to True):
(1,1), (-2,4), (-3,-2), (2,-1), (1,1)
import math
def findSlope(A,B):
slopeVal = (B[1]-A[1])/B[0]-A[0]
return slopeVal
def findSum(distance): # sum of all linesegments
sumval = 0
for k in distance:
sumval += distance[k]
return sumval
def findDist(point1,point2): # distance between 2 points
return (math.sqrt((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2))
def linelength (tupleList,start):
distance = {}
if start:
for point in tupleList:
slopeVal = findSlope((0,0),point)
if slopeVal in distance.keys(): # if there are no points in the given list with calc slope add it in available slopes
distance[slopeVal] = max(distance[slopeVal],findDist((0,0),point))
else: # if multiple points are with same slope then pick the largest line segment that passes through point and lies in the given list
distance[slopeVal] = findDist((0,0),point)
return findSum(distance)
else:
for i in range(1,len(tupleList)):
slopeVal = findSlope(tupleList[0],tupleList[i])
if slopeVal in distance.keys(): # if there are no points in the given list with calc slope add it in available slopes
distance[slopeVal] = max(distance[slopeVal],findDist(tupleList[0],tupleList[i]))
else: # if multiple points are with same slope then pick the largest line segment that passes through point and lies in the given list
distance[slopeVal] = findDist(tupleList[0],tupleList[i])
return findSum(distance)
return 0
def main():
tupleList = [(1,1), (-2,4), (-3,-2), (2,-1), (1,1)]
dist = linelength(tupleList,True)
print(dist)
main()
Comment in case of any doubts, Please upvote