In: Computer Science
PYTHON!
Exercise 3 - Total Line length
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)
PreviousNext
In this program, we have to find the length of the line connecting the given points in the argument list of the function lineLength().
To do this , we must use the argument *argv in the function. This argument will take variable length of points argument list. Remember that the user can provide as many points as they want to this function.
Then, we will define a variable named dist and set it to 0. This variable will store the lenght of the connecting line.
Then, loop through each point in the argument list, and find the distance between the current point and point in the next index. This distance will be added to the dist variable.
Finally, if start parameter is True, then add the distance between the first point and the origin to the dist variable.
dist variable will be returned from the function
In main() function, call lineLenght() with the points given in question, that is , (1,1), (-2,4), (-3,-2), (2,-1), (1,1). Once call it with start set to False, and once more with start set to True. Print both the results
program:
def lineLength(*argv,start = False):
points = argv
dist = 0
for i in range(len(points)-1):
dist_ = (points[i+1][0]-points[i][0])**2 +
(points[i+1][1]-points[i][1])**2
dist_ = dist_**0.5
dist += dist_
if start:
dist_ = (points[0][0])**2 + (points[0][1])**2
dist_ = dist_**0.5
dist += dist_
return dist
def main():
dist = lineLength((1,1), (-2,4), (-3,-2), (2,-1), (1,1))
print(f"Length of line connecting given points when start is False:
{dist}")
dist = lineLength((1,1), (-2,4), (-3,-2), (2,-1),
(1,1),start=True)
print(f"Length of line connecting given points when start is True:
{dist}")
main()
output: