Skip to content

Instantly share code, notes, and snippets.

@mdecourse
Last active November 20, 2021 13:23
Show Gist options
  • Save mdecourse/0229a8a017091476a79700b8a190f185 to your computer and use it in GitHub Desktop.
Save mdecourse/0229a8a017091476a79700b8a190f185 to your computer and use it in GitHub Desktop.
Python searching algorithms
# from https://github.com/joeyajames/Python/blob/master/bfs.py
class Vertex:
def __init__(self, n):
self.name = n
self.neighbors = list()
self.distance = 9999
self.color = 'black'
def add_neighbor(self, v):
if v not in self.neighbors:
self.neighbors.append(v)
self.neighbors.sort()
class Graph:
vertices = {}
def add_vertex(self, vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
return True
else:
return False
def add_edge(self, u, v):
if u in self.vertices and v in self.vertices:
for key, value in self.vertices.items():
if key == u:
value.add_neighbor(v)
if key == v:
value.add_neighbor(u)
return True
else:
return False
def print_graph(self):
for key in sorted(list(self.vertices.keys())):
print(key + str(self.vertices[key].neighbors) + " " + str(self.vertices[key].distance))
def bfs(self, vert):
q = list()
vert.distance = 0
vert.color = 'red'
for v in vert.neighbors:
self.vertices[v].distance = vert.distance + 1
q.append(v)
while len(q) > 0:
u = q.pop(0)
node_u = self.vertices[u]
node_u.color = 'red'
for v in node_u.neighbors:
node_v = self.vertices[v]
if node_v.color == 'black':
q.append(v)
if node_v.distance > node_u.distance + 1:
node_v.distance = node_u.distance + 1
g = Graph()
a = Vertex('A')
g.add_vertex(a)
g.add_vertex(Vertex('B'))
for i in range(ord('A'), ord('K')):
g.add_vertex(Vertex(chr(i)))
edges = ['AB', 'AE', 'BF', 'CG', 'DE', 'DH', 'EH', 'FG', 'FI', 'FJ', 'GJ', 'HI']
for edge in edges:
g.add_edge(edge[:1], edge[1:])
g.bfs(a)
g.print_graph()
# 利用 input() 取使用者輸入, 而且利用輸入字串說明要求
input_str = input("請輸入至少8個字元字串, 包含大小寫英文字母, 數字以及特殊符號")
# from https://stackoverflow.com/questions/17140408/if-statement-to-check-whether-a-string-has-a-capital-letter-a-lower-case-letter/17140466
# and https://stackoverflow.com/questions/57062794/how-to-check-if-a-string-has-any-special-characters/57062899
# 宣告 sp_char 為必須包含的特殊字元
sp_char = "!@#$%^&*()-+?_=,<>/"
# 定義一個查驗函式, 必須分別符合輸入要求的字串才會傳回 True
def check_str(s):
return (any(x.isupper() for x in s) and any(x.islower() for x in s) and any(x.isdigit() for x in s) and len(s) >= 8 and any(x in sp_char for x in s))
# 當使用者輸入不符合要求時, 無法跳出輸入迴圈
while check_str(input_str) != True:
input_str = input("請輸入至少8個字元字串, 包含大小寫英文字母, 數字以及特殊符號")
# 一旦使用者輸入符合要求的字串後 (即 check_str(input_str) 傳回 True, 則印出使用者的輸入字串
print("你輸入符合\"至少8個字元字串, 包含大小寫英文字母, 數字以及特殊符號\"要求的字串為:", input_str)
# sum 初始值設為 0
sum = 0
init = 1
upto = 100
# 利用 for 重複迴圈與變數加法進行累加
for i in range(init, upto+1):
sum = sum + i
print("從" + str(init) + "累加到" + str(upto) + "=" + str(sum))
sum = 1+2+3+4+5+6+7+8+9+10
print(sum)
#https://interactive-pathfinding.netlify.app/
#https://github.com/mdecourse/ai-snake
#https://github.com/mdecourse/Visualization-of-popular-algorithms-in-Python
import networkx as nx
import matplotlib.pyplot as plt
#BFS traversal
def BFS(G, source, pos):
visited = [False]*(len(G.nodes()))
queue = [] #a queue for BFS traversal
queue.append(source)
visited[source] = True
while queue:
curr_node = queue.pop(0)
for i in G[curr_node]: #iterates through all the possible vertices adjacent to the curr_node
if visited[i] == False:
queue.append(i)
visited[i] = True
# nx.draw_networkx_edges(G, pos, edgelist = [(curr_node,i)], width = 2.5, alpha = 0.6, edge_color = 'r')
return
#takes input from the file and creates a weighted graph
def CreateGraph():
G = nx.DiGraph()
f = open('input.txt')
n = int(f.readline())
wtMatrix = []
for i in range(n):
list1 = list(map(int, (f.readline()).split()))
wtMatrix.append(list1)
source = int(f.readline()) #source vertex from where BFS has to start
#Adds egdes along with their weights to the graph
for i in range(n):
for j in range(len(wtMatrix[i])):
if wtMatrix[i][j] > 0:
G.add_edge(i, j, length = wtMatrix[i][j])
return G, source
#draws the graph and displays the weights on the edges
def DrawGraph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
return pos
#main function
if __name__== "__main__":
G,source = CreateGraph()
pos = DrawGraph(G)
BFS(G, source, pos)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment