Repository navigation
Expand file tree
/
Copy pathProject
More file actions
119 lines (108 loc) · 4.21 KB
/
Copy pathProject
File metadata and controls
119 lines (108 loc) · 4.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import matplotlib.pyplot as plt
import heapq
cities = ["Bishkek", "Osh", "Jalal-Abad", "Karakol", "Naryn", "Talas", "Batken", "Tokmok", "Kochkor", "Isfana"]
paths = [
("Bishkek", "Osh", 200),
("Bishkek", "Jalal-Abad", 100),
("Osh", "Karakol", 290),
("Jalal-Abad", "Naryn", 150),
("Karakol", "Naryn", 400),
("Karakol", "Talas", 340),
("Naryn", "Batken", 260),
("Talas", "Batken", 500),
("Batken", "Tokmok", 430),
("Tokmok", "Kochkor", 230),
("Kochkor", "Isfana", 380),
("Bishkek", "Isfana", 150),
("Osh", "Kochkor", 120),
("Jalal-Abad", "Tokmok", 210),
("Talas", "Isfana", 140),
]
def puti(cities, paths):
print("Возможные пути:")
for i in paths:
print(f"Путь от: {i[0]} -----> до {i[1]}, расстояние между городами {i[2]}")
print()
def deikstra(cities,paths, start, end):
distances ={}
for i in cities:
distances[i]= float('inf')
distances[start] =0
pq = [(0,start)]
prev = {}
for i in cities:
prev[i] = None
while pq:
cdis,ccity =heapq.heappop(pq)
if ccity==end:
break
for i in paths:
if i[0]==ccity:
neigh= i[1]
j = cdis+i[2]
if j <distances[neigh]:
distances[neigh]= j
prev[neigh]= ccity
heapq.heappush(pq,(j,neigh))
elif i[1]==ccity:
neigh =i[0]
j = cdis+ i[2]
if j<distances[neigh]:
distances[neigh]= j
prev[neigh]=ccity
heapq.heappush(pq,(j, neigh))
path=[]
current= end
while current:
path.insert(0,current)
current= prev[current]
if distances[end] ==float('inf'):
return None,None
return path,distances[end]
print("Приветствуем!")
print("Перед вами карта городов и их пути:")
puti(cities,paths)
while True:
print("Опции:")
print("1. Найти кратчайший путь")
print("2. Добавить город")
print("3. Добавить путь между городами")
print("4. Возможные пути")
print("5. Получите кратчайшие пути из одного города во все остальные")
print("6. Выход")
choice = input("Выберите одну из опций (1-6): ")
if choice=='1':
start= input("Из какого года хотите начать?: ")
end =input("Введите конечный город: ")
if start in cities and end in cities:
p ,d = deikstra(cities,paths,start, end)
if p:
print(f"Самый короткий путь от {start} до {end} пути {p} с расстоянием {d}.")
else:
print("Невозможно попасть в этот город.")
else:
print("Один из городов не существует в приложении.")
elif choice == '2':
new_city = input("Введите название города: ")
if new_city in cities:
print("Город уже существует.")
else:
cities.append(new_city)
print(f"Город {new_city} был успешно добавлен.")
elif choice == '3':
city1 = input("Первый город: ")
city2 = input("Второй город: ")
d = int(input("Дистанция между городами: "))
if city1 in cities and city2 in cities:
paths.append((city1, city2, d))
print(f"Путь от {city1} до {city2} с расстоянием {d} был успешно добавлен.")
else:
print("Одного или более введенных городов несуществует.")
elif choice == '4':
print("Возможные пути::")
puti(cities, paths)
elif choice == '6':
print("До встречи!")
break
else:
print("Неправильный ввод. Повторите попытку.")