mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-05 09:21:13 +08:00
Pyupgrade to Python 3.9 (#4718)
* Pyupgrade to Python 3.9 * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
@ -13,7 +13,7 @@ def initialize_unweighted_directed_graph(
|
||||
graph[i + 1] = []
|
||||
|
||||
for e in range(edge_count):
|
||||
x, y = [int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")]
|
||||
x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> "))
|
||||
graph[x].append(y)
|
||||
return graph
|
||||
|
||||
@ -26,7 +26,7 @@ def initialize_unweighted_undirected_graph(
|
||||
graph[i + 1] = []
|
||||
|
||||
for e in range(edge_count):
|
||||
x, y = [int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")]
|
||||
x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> "))
|
||||
graph[x].append(y)
|
||||
graph[y].append(x)
|
||||
return graph
|
||||
@ -40,14 +40,14 @@ def initialize_weighted_undirected_graph(
|
||||
graph[i + 1] = []
|
||||
|
||||
for e in range(edge_count):
|
||||
x, y, w = [int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")]
|
||||
x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> "))
|
||||
graph[x].append((y, w))
|
||||
graph[y].append((x, w))
|
||||
return graph
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n, m = [int(i) for i in _input("Number of nodes and edges: ")]
|
||||
n, m = (int(i) for i in _input("Number of nodes and edges: "))
|
||||
|
||||
graph_choice = int(
|
||||
_input(
|
||||
|
@ -11,7 +11,7 @@ def check_negative_cycle(
|
||||
graph: list[dict[str, int]], distance: list[float], edge_count: int
|
||||
):
|
||||
for j in range(edge_count):
|
||||
u, v, w = [graph[j][k] for k in ["src", "dst", "weight"]]
|
||||
u, v, w = (graph[j][k] for k in ["src", "dst", "weight"])
|
||||
if distance[u] != float("inf") and distance[u] + w < distance[v]:
|
||||
return True
|
||||
return False
|
||||
@ -38,7 +38,7 @@ def bellman_ford(
|
||||
|
||||
for i in range(vertex_count - 1):
|
||||
for j in range(edge_count):
|
||||
u, v, w = [graph[j][k] for k in ["src", "dst", "weight"]]
|
||||
u, v, w = (graph[j][k] for k in ["src", "dst", "weight"])
|
||||
|
||||
if distance[u] != float("inf") and distance[u] + w < distance[v]:
|
||||
distance[v] = distance[u] + w
|
||||
@ -62,10 +62,10 @@ if __name__ == "__main__":
|
||||
|
||||
for i in range(E):
|
||||
print("Edge ", i + 1)
|
||||
src, dest, weight = [
|
||||
src, dest, weight = (
|
||||
int(x)
|
||||
for x in input("Enter source, destination, weight: ").strip().split(" ")
|
||||
]
|
||||
)
|
||||
graph[i] = {"src": src, "dst": dest, "weight": weight}
|
||||
|
||||
source = int(input("\nEnter shortest path source:").strip())
|
||||
|
@ -1,13 +1,13 @@
|
||||
from collections import deque
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Union
|
||||
|
||||
"""
|
||||
Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
|
||||
0-1-graph is the weighted graph with the weights equal to 0 or 1.
|
||||
Link: https://codeforces.com/blog/entry/22276
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
@ -59,7 +59,7 @@ class AdjacencyList:
|
||||
|
||||
self._graph[from_vertex].append(Edge(to_vertex, weight))
|
||||
|
||||
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> Optional[int]:
|
||||
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int | None:
|
||||
"""
|
||||
Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
|
||||
1 1 1
|
||||
@ -107,7 +107,7 @@ class AdjacencyList:
|
||||
ValueError: No path from start_vertex to finish_vertex.
|
||||
"""
|
||||
queue = deque([start_vertex])
|
||||
distances: list[Union[int, None]] = [None] * self.size
|
||||
distances: list[int | None] = [None] * self.size
|
||||
distances[start_vertex] = 0
|
||||
|
||||
while queue:
|
||||
|
@ -1,15 +1,12 @@
|
||||
"""
|
||||
https://en.wikipedia.org/wiki/Bidirectional_search
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from math import sqrt
|
||||
|
||||
# 1 for manhattan, 0 for euclidean
|
||||
from typing import Optional
|
||||
|
||||
HEURISTIC = 0
|
||||
|
||||
grid = [
|
||||
@ -50,7 +47,7 @@ class Node:
|
||||
goal_x: int,
|
||||
goal_y: int,
|
||||
g_cost: int,
|
||||
parent: Optional[Node],
|
||||
parent: Node | None,
|
||||
) -> None:
|
||||
self.pos_x = pos_x
|
||||
self.pos_y = pos_y
|
||||
@ -157,7 +154,7 @@ class AStar:
|
||||
)
|
||||
return successors
|
||||
|
||||
def retrace_path(self, node: Optional[Node]) -> list[TPosition]:
|
||||
def retrace_path(self, node: Node | None) -> list[TPosition]:
|
||||
"""
|
||||
Retrace the path from parents to parents until start node
|
||||
"""
|
||||
|
@ -1,11 +1,9 @@
|
||||
"""
|
||||
https://en.wikipedia.org/wiki/Bidirectional_search
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
Path = list[tuple[int, int]]
|
||||
|
||||
@ -24,7 +22,7 @@ delta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
|
||||
|
||||
class Node:
|
||||
def __init__(
|
||||
self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Optional[Node]
|
||||
self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Node | None
|
||||
):
|
||||
self.pos_x = pos_x
|
||||
self.pos_y = pos_y
|
||||
@ -57,7 +55,7 @@ class BreadthFirstSearch:
|
||||
self.node_queue = [self.start]
|
||||
self.reached = False
|
||||
|
||||
def search(self) -> Optional[Path]:
|
||||
def search(self) -> Path | None:
|
||||
while self.node_queue:
|
||||
current_node = self.node_queue.pop(0)
|
||||
|
||||
@ -93,7 +91,7 @@ class BreadthFirstSearch:
|
||||
)
|
||||
return successors
|
||||
|
||||
def retrace_path(self, node: Optional[Node]) -> Path:
|
||||
def retrace_path(self, node: Node | None) -> Path:
|
||||
"""
|
||||
Retrace the path from parents to parents until start node
|
||||
"""
|
||||
@ -125,7 +123,7 @@ class BidirectionalBreadthFirstSearch:
|
||||
self.bwd_bfs = BreadthFirstSearch(goal, start)
|
||||
self.reached = False
|
||||
|
||||
def search(self) -> Optional[Path]:
|
||||
def search(self) -> Path | None:
|
||||
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
|
||||
current_fwd_node = self.fwd_bfs.node_queue.pop(0)
|
||||
current_bwd_node = self.bwd_bfs.node_queue.pop(0)
|
||||
|
@ -1,13 +1,12 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
""" Author: OMKAR PATHAK """
|
||||
|
||||
from typing import Dict, List, Set
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class Graph:
|
||||
def __init__(self) -> None:
|
||||
self.vertices: Dict[int, List[int]] = {}
|
||||
self.vertices: dict[int, list[int]] = {}
|
||||
|
||||
def print_graph(self) -> None:
|
||||
"""
|
||||
@ -35,7 +34,7 @@ class Graph:
|
||||
else:
|
||||
self.vertices[from_vertex] = [to_vertex]
|
||||
|
||||
def bfs(self, start_vertex: int) -> Set[int]:
|
||||
def bfs(self, start_vertex: int) -> set[int]:
|
||||
"""
|
||||
>>> g = Graph()
|
||||
>>> g.add_edge(0, 1)
|
||||
|
@ -3,8 +3,6 @@ from a given source node to a target node in an unweighted graph.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
graph = {
|
||||
"A": ["B", "C", "E"],
|
||||
"B": ["A", "D", "E"],
|
||||
@ -24,7 +22,7 @@ class Graph:
|
||||
"""
|
||||
self.graph = graph
|
||||
# mapping node to its parent in resulting breadth first tree
|
||||
self.parent: dict[str, Optional[str]] = {}
|
||||
self.parent: dict[str, str | None] = {}
|
||||
self.source_vertex = source_vertex
|
||||
|
||||
def breath_first_search(self) -> None:
|
||||
|
@ -1,11 +1,8 @@
|
||||
"""Non recursive implementation of a DFS algorithm."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Set
|
||||
|
||||
|
||||
def depth_first_search(graph: dict, start: str) -> Set[str]:
|
||||
def depth_first_search(graph: dict, start: str) -> set[str]:
|
||||
"""Depth First Search on Graph
|
||||
:param graph: directed graph in dictionary format
|
||||
:param start: starting vertex as a string
|
||||
|
@ -4,8 +4,6 @@ https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
Path = list[tuple[int, int]]
|
||||
|
||||
grid = [
|
||||
@ -44,7 +42,7 @@ class Node:
|
||||
goal_x: int,
|
||||
goal_y: int,
|
||||
g_cost: float,
|
||||
parent: Optional[Node],
|
||||
parent: Node | None,
|
||||
):
|
||||
self.pos_x = pos_x
|
||||
self.pos_y = pos_y
|
||||
@ -93,7 +91,7 @@ class GreedyBestFirst:
|
||||
|
||||
self.reached = False
|
||||
|
||||
def search(self) -> Optional[Path]:
|
||||
def search(self) -> Path | None:
|
||||
"""
|
||||
Search for the path,
|
||||
if a path is not found, only the starting position is returned
|
||||
@ -156,7 +154,7 @@ class GreedyBestFirst:
|
||||
)
|
||||
return successors
|
||||
|
||||
def retrace_path(self, node: Optional[Node]) -> Path:
|
||||
def retrace_path(self, node: Node | None) -> Path:
|
||||
"""
|
||||
Retrace the path from parents to parents until start node
|
||||
"""
|
||||
|
@ -40,7 +40,7 @@ if __name__ == "__main__": # pragma: no cover
|
||||
edges = []
|
||||
|
||||
for _ in range(num_edges):
|
||||
node1, node2, cost = [int(x) for x in input().strip().split()]
|
||||
node1, node2, cost = (int(x) for x in input().strip().split())
|
||||
edges.append((node1, node2, cost))
|
||||
|
||||
kruskal(num_nodes, edges)
|
||||
|
@ -6,9 +6,10 @@ edges in the tree is minimized. The algorithm operates by building this tree one
|
||||
at a time, from an arbitrary starting vertex, at each step adding the cheapest possible
|
||||
connection from the tree to another vertex.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sys import maxsize
|
||||
from typing import Generic, Optional, TypeVar
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
@ -219,7 +220,7 @@ class GraphUndirectedWeighted(Generic[T]):
|
||||
|
||||
def prims_algo(
|
||||
graph: GraphUndirectedWeighted[T],
|
||||
) -> tuple[dict[T, int], dict[T, Optional[T]]]:
|
||||
) -> tuple[dict[T, int], dict[T, T | None]]:
|
||||
"""
|
||||
>>> graph = GraphUndirectedWeighted()
|
||||
|
||||
@ -240,7 +241,7 @@ def prims_algo(
|
||||
"""
|
||||
# prim's algorithm for minimum spanning tree
|
||||
dist: dict[T, int] = {node: maxsize for node in graph.connections}
|
||||
parent: dict[T, Optional[T]] = {node: None for node in graph.connections}
|
||||
parent: dict[T, T | None] = {node: None for node in graph.connections}
|
||||
|
||||
priority_queue: MinPriorityQueue[T] = MinPriorityQueue()
|
||||
for node, weight in dist.items():
|
||||
|
@ -43,7 +43,7 @@ def page_rank(nodes, limit=3, d=0.85):
|
||||
print(f"======= Iteration {i + 1} =======")
|
||||
for j, node in enumerate(nodes):
|
||||
ranks[node.name] = (1 - d) + d * sum(
|
||||
[ranks[ib] / outbounds[ib] for ib in node.inbound]
|
||||
ranks[ib] / outbounds[ib] for ib in node.inbound
|
||||
)
|
||||
print(ranks)
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
from typing import List
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def dfs(u):
|
||||
@ -39,16 +39,16 @@ if __name__ == "__main__":
|
||||
# n - no of nodes, m - no of edges
|
||||
n, m = list(map(int, input().strip().split()))
|
||||
|
||||
graph: List[List[int]] = [[] for i in range(n)] # graph
|
||||
reversedGraph: List[List[int]] = [[] for i in range(n)] # reversed graph
|
||||
graph: list[list[int]] = [[] for i in range(n)] # graph
|
||||
reversedGraph: list[list[int]] = [[] for i in range(n)] # reversed graph
|
||||
# input graph data (edges)
|
||||
for i in range(m):
|
||||
u, v = list(map(int, input().strip().split()))
|
||||
graph[u].append(v)
|
||||
reversedGraph[v].append(u)
|
||||
|
||||
stack: List[int] = []
|
||||
visit: List[bool] = [False] * n
|
||||
scc: List[int] = []
|
||||
component: List[int] = []
|
||||
stack: list[int] = []
|
||||
visit: list[bool] = [False] * n
|
||||
scc: list[int] = []
|
||||
component: list[int] = []
|
||||
print(kosaraju())
|
||||
|
Reference in New Issue
Block a user