简体   繁体   中英

Function to calculate the average distance from a set of tuples (Python)

I need to implement a function that from a given set of points, specified by a pair of integers returns the average distance between the points. If there are less points that 2 in the set, it raises a Value Error. distance is computed using the formula: d=sqrt ((x1−x2)**2+(y1−y2)**2)

I'm struggling to get the loop to work, but it gives me an error that types.Genericaliases has no len() . Realised that this has something to do with the input being a set, but now I don't know how to resolve this:

def average_distance(points: set[tuple[int,int]]) -> float:



from math import sqrt
  
  points = list[input()]
  list_dist =[] 


for index in range(0, len(points)):
    coordinate = points[index] # tuple in the set points
    x1 = coordinate[0] # first el in the pair
    y1 = coordinate[1] # second el in the pair
    next_coordinate = points[index +1]
    x2 = next_coordinate[0]
    y2 = next_coordinate[1]
    
    distance = math.sqrt(((x1-x2)**2)+((y1-y2)**2))
    list_dist.append(distance)
  
  total_dist = 0
  for dist in distance:
    total_dist += dist 


avg_dist = total_dist//(len(distance))
  return avg_dist

So

print (average_distance({(1,2), (3,4), (5,6)}))

Expected output:

3.7712

Would be grateful for your advice on this.

Many thanks

Shorter solution using the library more:

from statistics import mean
from math import dist
from itertools import combinations, starmap

def average_distance(points):
    return mean(starmap(dist, combinations(points, 2)))
    
print(average_distance({(1,2), (3,4), (5,6)}))

Output:

3.771236166328254

Here is my implementation for both the average distance between every group of two points given sequentially and all combinations of points. Take a look.

from itertools import combinations
from math import sqrt
from typing import List, NamedTuple


class Point(NamedTuple):
    x: float
    y: float


def distance(p1: Point, p2: Point) -> float:
    return sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2)


def avg_dist_between_all_points(points: List[Point]) -> float:
    c = list(combinations(points, 2))
    return sum(distance(*pair) for pair in c) / len(c)


def avg_dist_between_seq_points(points: List[Point]) -> float:
    c = [points[i : i + 2] for i in range(len(points) - 1)]
    return sum(distance(*pair) for pair in c) / len(c)


if __name__ == "__main__":
    input_str = input("points (ex: 1,2 3,4 5,6): ")
    point_strs = input_str.split(" ")
    points: List[Point] = []
    for s in point_strs:
        x, y = s.split(",")
        points.append(Point(float(x), float(y)))
    print(avg_dist_between_all_points(points))
    print(avg_dist_between_seq_points(points))

This yields:

➜ ./avgdist.py
points (ex: 1,2 3,4 5,6): 1,2 3,4 5,6
3.771236166328254
2.8284271247461903

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM