Skip to content

Commit

Permalink
Update travelling_salesman_problem.py
Browse files Browse the repository at this point in the history
  • Loading branch information
OmMahajan29 authored Oct 10, 2024
1 parent d76d039 commit 7f43fa4
Showing 1 changed file with 5 additions and 14 deletions.
19 changes: 5 additions & 14 deletions dynamic_programming/travelling_salesman_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,28 @@

from functools import lru_cache


def tsp(distances: list[list[int]]) -> int:

Check failure on line 5 in dynamic_programming/travelling_salesman_problem.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

dynamic_programming/travelling_salesman_problem.py:3:1: I001 Import block is un-sorted or un-formatted
"""
Solves the Travelling Salesman Problem (TSP) using dynamic programming and bitmasking.
Solves the Travelling Salesman Problem (TSP) using

Check failure on line 7 in dynamic_programming/travelling_salesman_problem.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

dynamic_programming/travelling_salesman_problem.py:7:55: W291 Trailing whitespace
dynamic programming and bitmasking.
Args:
distances: A 2D list where distances[i][j] represents the distance between city i and city j.
distances: A 2D list where distances[i][j] represents the

Check failure on line 10 in dynamic_programming/travelling_salesman_problem.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

dynamic_programming/travelling_salesman_problem.py:10:66: W291 Trailing whitespace
distance between city i and city j.
Returns:
The minimum cost to complete the tour visiting all cities.
Raises:
ValueError: If any distance is negative.
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
80
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
69
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
ValueError: Distance cannot be negative
"""
n = len(distances)
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
raise ValueError("Distance cannot be negative")

visited_all = (1 << n) - 1

@lru_cache(None)
Expand All @@ -45,11 +40,7 @@ def visit(city: int, mask: int) -> int:
)
min_cost = min(min_cost, new_cost)
return min_cost

return visit(0, 1) # Start from city 0 with only city 0 visited


if __name__ == "__main__":
import doctest

doctest.testmod()

0 comments on commit 7f43fa4

Please sign in to comment.