translation: Add Python and Java code for EN version (#1345)

* Add the intial translation of code of all the languages

* test

* revert

* Remove

* Add Python and Java code for EN version
This commit is contained in:
Yudong Jin
2024-05-06 05:21:51 +08:00
committed by GitHub
parent b5e198db7d
commit 1c0f350ad6
174 changed files with 12349 additions and 0 deletions

View File

@ -0,0 +1,111 @@
"""
File: graph_adjacency_list.py
Created Time: 2023-02-23
Author: krahets (krahets@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import Vertex, vals_to_vets
class GraphAdjList:
"""Undirected graph class based on adjacency list"""
def __init__(self, edges: list[list[Vertex]]):
"""Constructor"""
# Adjacency list, key: vertex, value: all adjacent vertices of that vertex
self.adj_list = dict[Vertex, list[Vertex]]()
# Add all vertices and edges
for edge in edges:
self.add_vertex(edge[0])
self.add_vertex(edge[1])
self.add_edge(edge[0], edge[1])
def size(self) -> int:
"""Get the number of vertices"""
return len(self.adj_list)
def add_edge(self, vet1: Vertex, vet2: Vertex):
"""Add edge"""
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
raise ValueError()
# Add edge vet1 - vet2
self.adj_list[vet1].append(vet2)
self.adj_list[vet2].append(vet1)
def remove_edge(self, vet1: Vertex, vet2: Vertex):
"""Remove edge"""
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
raise ValueError()
# Remove edge vet1 - vet2
self.adj_list[vet1].remove(vet2)
self.adj_list[vet2].remove(vet1)
def add_vertex(self, vet: Vertex):
"""Add vertex"""
if vet in self.adj_list:
return
# Add a new linked list to the adjacency list
self.adj_list[vet] = []
def remove_vertex(self, vet: Vertex):
"""Remove vertex"""
if vet not in self.adj_list:
raise ValueError()
# Remove the vertex vet's corresponding linked list from the adjacency list
self.adj_list.pop(vet)
# Traverse other vertices' linked lists, removing all edges containing vet
for vertex in self.adj_list:
if vet in self.adj_list[vertex]:
self.adj_list[vertex].remove(vet)
def print(self):
"""Print the adjacency list"""
print("Adjacency list =")
for vertex in self.adj_list:
tmp = [v.val for v in self.adj_list[vertex]]
print(f"{vertex.val}: {tmp},")
"""Driver Code"""
if __name__ == "__main__":
# Initialize undirected graph
v = vals_to_vets([1, 3, 2, 5, 4])
edges = [
[v[0], v[1]],
[v[0], v[3]],
[v[1], v[2]],
[v[2], v[3]],
[v[2], v[4]],
[v[3], v[4]],
]
graph = GraphAdjList(edges)
print("\nAfter initialization, the graph is")
graph.print()
# Add edge
# Vertices 1, 2 i.e., v[0], v[2]
graph.add_edge(v[0], v[2])
print("\nAfter adding edge 1-2, the graph is")
graph.print()
# Remove edge
# Vertices 1, 3 i.e., v[0], v[1]
graph.remove_edge(v[0], v[1])
print("\nAfter removing edge 1-3, the graph is")
graph.print()
# Add vertex
v5 = Vertex(6)
graph.add_vertex(v5)
print("\nAfter adding vertex 6, the graph is")
graph.print()
# Remove vertex
# Vertex 3 i.e., v[1]
graph.remove_vertex(v[1])
print("\nAfter removing vertex 3, the graph is")
graph.print()

View File

@ -0,0 +1,116 @@
"""
File: graph_adjacency_matrix.py
Created Time: 2023-02-23
Author: krahets (krahets@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import Vertex, print_matrix
class GraphAdjMat:
"""Undirected graph class based on adjacency matrix"""
def __init__(self, vertices: list[int], edges: list[list[int]]):
"""Constructor"""
# Vertex list, elements represent "vertex value", index represents "vertex index"
self.vertices: list[int] = []
# Adjacency matrix, row and column indices correspond to "vertex index"
self.adj_mat: list[list[int]] = []
# Add vertex
for val in vertices:
self.add_vertex(val)
# Add edge
# Please note, edges elements represent vertex indices, corresponding to vertices elements indices
for e in edges:
self.add_edge(e[0], e[1])
def size(self) -> int:
"""Get the number of vertices"""
return len(self.vertices)
def add_vertex(self, val: int):
"""Add vertex"""
n = self.size()
# Add new vertex value to the vertex list
self.vertices.append(val)
# Add a row to the adjacency matrix
new_row = [0] * n
self.adj_mat.append(new_row)
# Add a column to the adjacency matrix
for row in self.adj_mat:
row.append(0)
def remove_vertex(self, index: int):
"""Remove vertex"""
if index >= self.size():
raise IndexError()
# Remove vertex at `index` from the vertex list
self.vertices.pop(index)
# Remove the row at `index` from the adjacency matrix
self.adj_mat.pop(index)
# Remove the column at `index` from the adjacency matrix
for row in self.adj_mat:
row.pop(index)
def add_edge(self, i: int, j: int):
"""Add edge"""
# Parameters i, j correspond to vertices element indices
# Handle index out of bounds and equality
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
raise IndexError()
# In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., satisfies (i, j) == (j, i)
self.adj_mat[i][j] = 1
self.adj_mat[j][i] = 1
def remove_edge(self, i: int, j: int):
"""Remove edge"""
# Parameters i, j correspond to vertices element indices
# Handle index out of bounds and equality
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
raise IndexError()
self.adj_mat[i][j] = 0
self.adj_mat[j][i] = 0
def print(self):
"""Print adjacency matrix"""
print("Vertex list =", self.vertices)
print("Adjacency matrix =")
print_matrix(self.adj_mat)
"""Driver Code"""
if __name__ == "__main__":
# Initialize undirected graph
# Please note, edges elements represent vertex indices, corresponding to vertices elements indices
vertices = [1, 3, 2, 5, 4]
edges = [[0, 1], [0, 3], [1, 2], [2, 3], [2, 4], [3, 4]]
graph = GraphAdjMat(vertices, edges)
print("\nAfter initialization, the graph is")
graph.print()
# Add edge
# Indices of vertices 1, 2 are 0, 2 respectively
graph.add_edge(0, 2)
print("\nAfter adding edge 1-2, the graph is")
graph.print()
# Remove edge
# Indices of vertices 1, 3 are 0, 1 respectively
graph.remove_edge(0, 1)
print("\nAfter removing edge 1-3, the graph is")
graph.print()
# Add vertex
graph.add_vertex(6)
print("\nAfter adding vertex 6, the graph is")
graph.print()
# Remove vertex
# Index of vertex 3 is 1
graph.remove_vertex(1)
print("\nAfter removing vertex 3, the graph is")
graph.print()

View File

@ -0,0 +1,64 @@
"""
File: graph_bfs.py
Created Time: 2023-02-23
Author: krahets (krahets@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import Vertex, vals_to_vets, vets_to_vals
from collections import deque
from graph_adjacency_list import GraphAdjList
def graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
"""Breadth-first traversal"""
# Use adjacency list to represent the graph, to obtain all adjacent vertices of a specified vertex
# Vertex traversal sequence
res = []
# Hash set, used to record visited vertices
visited = set[Vertex]([start_vet])
# Queue used to implement BFS
que = deque[Vertex]([start_vet])
# Starting from vertex vet, loop until all vertices are visited
while len(que) > 0:
vet = que.popleft() # Dequeue the vertex at the head of the queue
res.append(vet) # Record visited vertex
# Traverse all adjacent vertices of that vertex
for adj_vet in graph.adj_list[vet]:
if adj_vet in visited:
continue # Skip already visited vertices
que.append(adj_vet) # Only enqueue unvisited vertices
visited.add(adj_vet) # Mark the vertex as visited
# Return the vertex traversal sequence
return res
"""Driver Code"""
if __name__ == "__main__":
# Initialize undirected graph
v = vals_to_vets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
edges = [
[v[0], v[1]],
[v[0], v[3]],
[v[1], v[2]],
[v[1], v[4]],
[v[2], v[5]],
[v[3], v[4]],
[v[3], v[6]],
[v[4], v[5]],
[v[4], v[7]],
[v[5], v[8]],
[v[6], v[7]],
[v[7], v[8]],
]
graph = GraphAdjList(edges)
print("\nAfter initialization, the graph is")
graph.print()
# Breadth-first traversal
res = graph_bfs(graph, v[0])
print("\nBreadth-first traversal (BFS) vertex sequence is")
print(vets_to_vals(res))

View File

@ -0,0 +1,57 @@
"""
File: graph_dfs.py
Created Time: 2023-02-23
Author: krahets (krahets@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import Vertex, vets_to_vals, vals_to_vets
from graph_adjacency_list import GraphAdjList
def dfs(graph: GraphAdjList, visited: set[Vertex], res: list[Vertex], vet: Vertex):
"""Depth-first traversal helper function"""
res.append(vet) # Record visited vertex
visited.add(vet) # Mark the vertex as visited
# Traverse all adjacent vertices of that vertex
for adjVet in graph.adj_list[vet]:
if adjVet in visited:
continue # Skip already visited vertices
# Recursively visit adjacent vertices
dfs(graph, visited, res, adjVet)
def graph_dfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
"""Depth-first traversal"""
# Use adjacency list to represent the graph, to obtain all adjacent vertices of a specified vertex
# Vertex traversal sequence
res = []
# Hash set, used to record visited vertices
visited = set[Vertex]()
dfs(graph, visited, res, start_vet)
return res
"""Driver Code"""
if __name__ == "__main__":
# Initialize undirected graph
v = vals_to_vets([0, 1, 2, 3, 4, 5, 6])
edges = [
[v[0], v[1]],
[v[0], v[3]],
[v[1], v[2]],
[v[2], v[5]],
[v[4], v[5]],
[v[5], v[6]],
]
graph = GraphAdjList(edges)
print("\nAfter initialization, the graph is")
graph.print()
# Depth-first traversal
res = graph_dfs(graph, v[0])
print("\nDepth-first traversal (DFS) vertex sequence is")
print(vets_to_vals(res))