Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Functions
#1
Hello everyone
The only problem I have here is printing the distance between two points. The program asks the user to input 2 values and then appends those values together as a tuple to a list. Then when I need the distance, it is supposed to take the first value and the second and compute the distance. Then the second and the third. Then the third and the fourth and so on for as many tuples are in the list. However it only prints the distance of the first and second points. I know what I have right now doesn't work. Any ideas of how to do it better are greatly appreciated.
my program:
import math
from location import where_is_xy
#Below is the "main" function which acts as the entry point
l =[]
b = []
list4 = []
list5 = []
list6 = []
if __name__ == '__main__':
    flag = False
    try:
        while flag == False:
            x, y = [int(x) for x in input("Enter two numbers here seperated by space: ").split()]
            l.append((x,y))
            result = where_is_xy(x, y)
            list4.append((x, y))
                      
    except Exception:
        flag = True
        print("Points:", l)
        for i in range(0, len(l)):
            print(l[i], "%5s" % result[i])

            
    print("Distance:")
    for i in range(0, len(l) - 1):
        print(l[i], l[i + 1], "=", "{:,.2f}".format(math.sqrt(((l[0][0] - l[1][0]) ** 2) + ((l[0][1] - l[1][1]) ** 2))))
location is a function that has no impact on the distance so I'm not posting it here.
Reply
#2
Nevermind I got it. The answer was to set i and i + 1 equal to a variable. Then it will use the variable and thus input different points into the distance formula.
new code:
import math
from location import where_is_xy
#Below is the "main" function which acts as the entry point
l =[]
b = []
list4 = []
list5 = []
list6 = []
if __name__ == '__main__':
    flag = False
    try:
        while flag == False:
            x, y = [int(x) for x in input("Enter two numbers here seperated by space: ").split()]
            l.append((x,y))
            result = where_is_xy(x, y)
            list4.append((x, y))
                      
    except Exception:
        flag = True
        print("Points:", l)
        for i in range(0, len(l)):
            print(l[i], "%5s" % result[i])

            
    print("Distance:")
    for i in range(0, len(l) - 1):
        a = i
        b = i + 1
        print(l[i], l[i + 1], "=", "{:,.2f}".format(math.sqrt(((l[a][0] - l[b][0]) ** 2) + ((l[a][1] - l[b][1]) ** 2))))
       
Reply
#3
Why do you use such meaningless variable names like list4? What is it a list of and why the 4? Single letters are also generally bad (I'd say they're acceptable when they're in common use, like in equations). Choose names that convey the purpose of the things being named, because that helps people (including you) read and understand the code.
Reply
#4
Do you need to keep the points, or only compute the distance?

Flag does not exit the loop.
    try:
        while flag == False:
            x, y = [int(x) for x in input("Enter two numbers here seperated by space: ").split()]
            l.append((x,y))
            result = where_is_xy(x, y)
            list4.append((x, y))
                       
    except Exception:
        flag = True
The only way flag is set True is by raising an exception. Raising an exception jumps to the except which is outside the loop. You may as well loop using "while True:"

I would use zip to get consecutive points. Here "p" will be one point and "n" the next point. Read up on zip and list slices to understand how it works. Is one of my favorite Python tricks.
p, n = zip(l, l[1:])
If zip is too confusing you can use a variable to remember the previous point:
distance = 0
p = l[0]
for n in l[1:]:
    distance += ((n[0] - p[0])**2 + (n[1]-p[1])**2)**0.5
    p = n
And never use "l" (lower case L) as a variable name. It looks too much like 1 (one). For the same reason never use upper case "O" which looks a lot like zero (0).

You can use x**0.5 to do square root. No need to import the math library.
Reply
#5
You could use math.dist, which is made to calculate distances of two points with unlimited dimensions.
You can use this function also to calculate distances in 3d space.

Example:
try:
    from itertools import pairwise

    # https://docs.python.org/3/library/itertools.html#itertools.pairwise
except ImportError:
    # if you're using Python 3.10, you don't have pairwise
    # here a simple replacement of pairwise from the documentation
    from itertools import tee

    def pairwise(iterable):
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)


def calculate_and_print(coords):
    for p0, p1 in pairwise(coords):
        distance = math.dist(p0, p1)
        print(f"{p0} -> {p1} = {distance}")
Edit: I removed the full solution.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
Ooh, I like pairwise. That's even better than the zip/slice method I've been using. Oh no! New in version 3.10! I'm stuck with 3.8 for now. Gotta roll my own for now.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020