Python编写曼哈顿距离代码
时间: 2024-05-13 22:11:24 浏览: 25
曼哈顿距离是指在网格状的坐标系上两点之间的距离,也被称为街区距离或者城市街区距离。Python编写曼哈顿距离代码可以使用以下代码:
```python
def manhattan_distance(x1, y1, x2, y2):
return abs(x1 - y2)
```
其中,x1和y1是第一个点的坐标,x2和y2是第二个点的坐标。函数返回这两个点之间的曼哈顿距离。
相关问题
曼哈顿距离矩阵,python
以下是使用Python编写的计算曼哈顿距离矩阵的代码:
```python
def manhattan_distance_matrix(points):
n = len(points)
distance_matrix = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
distance_matrix[i][j] = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])
return distance_matrix
# 示例输入
points = [(1, 2), (3, 4), (5, 6)]
distance_matrix = manhattan_distance_matrix(points)
# 输出距离矩阵
for row in distance_matrix:
print(row)
```
在这段代码中,`points` 是一个包含点坐标的列表,其中每个点表示为一个二元组 `(x, y)`。`manhattan_distance_matrix` 函数接受这个点列表作为输入,并使用两层循环计算每对点之间的曼哈顿距离,并将结果存储在 `distance_matrix` 中。最后,通过遍历输出 `distance_matrix` 可以查看计算得到的曼哈顿距离矩阵。
使用Python编写一个能计算样本间欧式距离与曼哈顿距离的方法。
下面是Python代码实现:
```python
import numpy as np
def euclidean_distance(x1, x2):
"""
计算两个样本之间的欧式距离
:param x1: 样本1,类型为numpy数组
:param x2: 样本2,类型为numpy数组
:return: 欧式距离,类型为float
"""
return np.sqrt(np.sum(np.power(x1 - x2, 2)))
def manhattan_distance(x1, x2):
"""
计算两个样本之间的曼哈顿距离
:param x1: 样本1,类型为numpy数组
:param x2: 样本2,类型为numpy数组
:return: 曼哈顿距离,类型为float
"""
return np.sum(np.absolute(x1 - x2))
```
使用示例:
```python
# 计算欧式距离
x1 = np.array([1, 2, 3])
x2 = np.array([4, 5, 6])
print("欧式距离:", euclidean_distance(x1, x2))
# 计算曼哈顿距离
x1 = np.array([1, 2, 3])
x2 = np.array([4, 5, 6])
print("曼哈顿距离:", manhattan_distance(x1, x2))
```
输出结果:
```
欧式距离: 5.196152422706632
曼哈顿距离: 9
```