Skip to content

Commit 5ad7c44

Browse files
authored
Update travelling_salesman_problem.py
1 parent 4013b48 commit 5ad7c44

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
#!/usr/bin/env python3
2-
32
from functools import lru_cache
43

5-
64
def tsp(distances: list[list[int]]) -> int:
75
"""
86
Solves the Travelling Salesman Problem (TSP) using
@@ -16,25 +14,22 @@ def tsp(distances: list[list[int]]) -> int:
1614
Raises:
1715
ValueError: If any distance is negative.
1816
19-
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
20-
80
21-
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
22-
69
23-
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
24-
ValueError: Distance cannot be negative
17+
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
18+
80
19+
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
20+
69
21+
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
22+
ValueError: Distance cannot be negative
2523
"""
2624
n = len(distances)
2725
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
2826
raise ValueError("Distance cannot be negative")
29-
3027
visited_all = (1 << n) - 1
31-
3228
@lru_cache(None)
3329
def visit(city: int, mask: int) -> int:
3430
"""Recursively calculates the minimum cost to visit all cities."""
3531
if mask == visited_all:
3632
return distances[city][0] # Return to start
37-
3833
min_cost = float("inf") # Large value to compare against
3934
for next_city in range(n):
4035
if not mask & (1 << next_city): # If unvisited
@@ -43,11 +38,8 @@ def visit(city: int, mask: int) -> int:
4338
)
4439
min_cost = min(min_cost, new_cost)
4540
return int(min_cost) # Ensure returning an integer
46-
4741
return visit(0, 1) # Start from city 0 with city 0 visited
4842

49-
5043
if __name__ == "__main__":
5144
import doctest
52-
5345
doctest.testmod()

0 commit comments

Comments
 (0)