Task
Write a function that receives four parameters: x1, y1, x2, y2 which are all floating point values.
The function is called distance and returns (float) the distance between x1,y1 and x2,y2 on the cartesian coordinate plane.
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def dist(x1, y1, x2, y2): | |
x = x2-x1 | |
y = y2-y1 | |
z = (x**2) + (y**2) | |
ans= math.sqrt(z) | |
return ans | |
#MainProgramBelow | |
x1 = float(input("Write the x value for the first coordinate")) | |
y1 = float(input("Write the y value for the first coordinate")) | |
x2 = float(input("Write the x value for the second coordinate")) | |
y2 = float(input("Write the y value for the second coordinate")) | |
print("The distance in between the two coordinates is:", dist(x1, y1, x2, y2)) |
Solution using tuples:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Quiz09alternative | |
import math | |
def dist(a,b): | |
x = b[0] -a[0] | |
y = b[1] – a[1] | |
z = x**2 + y**2 | |
ans= math.sqrt(z) | |
return ans | |
#MainProgramBelow | |
x1 = float(input("Write the x value for the first coordinate")) | |
y1 = float(input("Write the y value for the first coordinate")) | |
a = (x1,y1) | |
x2 = float(input("Write the x value for the second coordinate")) | |
y2 = float(input("Write the y value for the second coordinate")) | |
b = (x2,y2) | |
print("The distance in between", a ,"and", b , "is:", dist(a,b)) |
Hey! I did exactly like you on the first part! Thanks for the second part, thanks to that I better understood tuples. Come visit my blog too 🙂
LikeLiked by 1 person
You’re welcome! Of course I’ll give a look.
LikeLike
I did not thought of solving the problem with tuples
LikeLike
Yeah, there are a lot of options
LikeLike