Помогите найти ошибку
from collections import defaultdict
def find_max_happiness_tour(V, E, p_values, routes):
graph = defaultdict(list)
for route in routes:
A, B = route[0], route[1]
graph[A].append((B, p_values[B-1]))
graph[B].append((A, p_values[A-1]))
max_happiness = 0
for start_city in range(1, V+1):
visited = set()
current_city = start_city
current_happiness = 0
for _ in range(4): # At most four days
visited.add(current_city)
max_neighbor_happiness = 0
next_city = None
for neighbor, happiness in graph[current_city]:
if neighbor not in visited and happiness > max_neighbor_happiness:
max_neighbor_happiness = happiness
next_city = neighbor
if next_city is not None:
current_city = next_city
current_happiness += max_neighbor_happiness
max_happiness = max(max_happiness, current_happiness)
return max_happiness
V = 5
E = 6
p_values = [3, 2, 4, 1, 5]
routes = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (1, 3)]
result = find_max_happiness_tour(V, E, p_values, routes)
print(result)
помогите, срочно надо


Ответы
Ответ:
у вас отсутствует return-инструкция после внутреннего цикла, что может привести к неправильным результатам. Вот исправленный вариант кода:
from collections import defaultdict
def find_max_happiness_tour(V, E, p_values, routes):
graph = defaultdict(list)
for route in routes:
A, B = route[0], route[1]
graph[A].append((B, p_values[B-1]))
graph[B].append((A, p_values[A-1]))
max_happiness = 0
for start_city in range(1, V+1):
visited = set()
current_city = start_city
current_happiness = 0
for _ in range(4): # At most four days
visited.add(current_city)
max_neighbor_happiness = 0
next_city = None
for neighbor, happiness in graph[current_city]:
if neighbor not in visited and happiness > max_neighbor_happiness:
max_neighbor_happiness = happiness
next_city = neighbor
if next_city is not None:
current_city = next_city
current_happiness += max_neighbor_happiness
max_happiness = max(max_happiness, current_happiness)
return max_happiness
V = 5
E = 6
p_values = [3, 2, 4, 1, 5]
routes = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (1, 3)]
result = find_max_happiness_tour(V, E, p_values, routes)
print(result)