Python:计算总距离路径

问题描述 投票:0回答:1

我有一个程序,用于计算Python Turtle的一组坐标的总距离。目前,我有一个名为def compute_distance的函数,该函数仅计算两点之间的距离。我需要:

  • 设置一个变量以保存总路径距离
  • 使用循环分别计算点的距离
  • 尝试并使用calculate_distance函数
  • 计算所有返回原始位置的路径

我将如何去做?我是Python的新手,但我了解大多数基础知识。这是我的程序最后显示的内容:

点之间的距离:72.59476565152615-但这是两个点之间的距离,而不是总和]

import math

selected_map = [(12, 34), (45, -55), (-89, 33), (60, 12)]

def calculate_distance(starting_x, starting_y, destination_x, destination_y):
    distance = math.hypot(destination_x - starting_x, destination_y - starting_y)  # calculates Euclidean distance (straight-line) distance between two points
    return distance

def calculate_path(selected_map):

- The code I am asking for help on needs to go here in this function



print (distance)

我有一个程序,用于计算Python Turtle的一组坐标的总距离。目前,我有一个名为def compute_distance的函数,该函数可计算...

python loops distance python-turtle
1个回答
0
投票
import math

def calculate_distance(starting_x, starting_y, destination_x, destination_y):
    distance = math.hypot(destination_x - starting_x, destination_y - starting_y)  # calculates Euclidean distance (straight-line) distance between two points
    return distance

def calculate_path(selected_map):
    total_distance = 0
    current_point = selected_map[0]
    for next_point in selected_map[1:]:
        total_distance += calculate_distance(
            current_point[0], current_point[1],
            next_point[0], next_point[1])
        current_point = next_point
    return total_distance

selected_map = [(12, 34), (45, -55), (-89, 33), (60, 12)]
distance = calculate_path(selected_map)

print (distance)
© www.soinside.com 2019 - 2024. All rights reserved.