更新代码

master
bettleChen 11 months ago
parent 7b16abeee3
commit eaabe65530

@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
# Time : 2023/10/30 15:49
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : X1.py

47
X2.py

@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
# Time : 2023/10/30 15:49
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : X2.py
# encoding: utf-8
# 第一题讲二进制数转换为10进制数
def binToDec_int(b):
d = 0
for i in range(len(b)):
# 请在此添加代码补全函数BinToDec_int()
# -----------Begin----------
if b[i] == '1':
d = d + 2 ** (len(b) - 1 - i)
# ------------End-----------
return d
def binToDec_float(b):
# 请在此添加代码补全函数BinToDec_int()
# -----------Begin----------
d = 0.0
for i in range(len(b)):
# 请在此添加代码补全函数BinToDec_int()
# -----------Begin----------
if b[i] == '1':
d = d + 2 ** (-(i+1))
# ------------End-----------
return d
if __name__ == '__main__':
tests = []
inputlist = input()
# print(type(inputlist))
# for i in inputlist:
# tests.append(str(i))
tests = inputlist.split(',')
for num in tests:
if '.' in num:
num1 = num.split('.')
print(binToDec_int(num1[0])+binToDec_float(num1[1]))
else:
print(binToDec_int(num))

282
X3.py

@ -1,205 +1,81 @@
# -*- encoding: utf-8 -*-
"""
@Author: packy945
@FileName: X3.py
@DateTime: 2023/7/12 14:07
@SoftWare: PyCharm
"""
# -*- encoding: utf-8 -*-
from head import *
class Node:
# 标记节点按钮
def node_mark_display(self):
for w in frame_right.winfo_children():
w.destroy()
# 清除右侧组件
curx = -1
y0 = 0.1
for i in d.Nodes:
if i[2] == 1:
curx = i[0]
lab = tk.Label(frame_right, text="节点操作", bg=RED, fg=BLACK, font=('微软雅黑', 20))
lab.place(relx=0.18, rely=0.02, width=200, height=30)
lab1 = tk.Label(frame_right, text=f"当前共有{len(d.Nodes)}个节点", bg=RED, fg=BLACK, font=('微软雅黑', 15))
lab1.place(relx=0.1, rely=0.0 + y0, width=200, height=30)
lab1 = tk.Label(frame_right, text="当前节点:", bg=RED, fg=BLACK, font=('微软雅黑', 12))
if curx == -1:
text = "未选择"
else:
text = f"{d.Nodes[curx][1]}"
lab2 = tk.Label(frame_right, text=text, bg=BLUE, fg=BLACK, font=('微软雅黑', 12))
lab1.place(relx=0.1, rely=0.05 + y0, width=80, height=30)
lab2.place(relx=0.4, rely=0.05 + y0, width=80, height=30)
B = tk.Button(frame_right, text="设置标签", command=lambda: self.node_rename())
B.place(relx=0.7, rely=0.05 + y0, width=80, height=30)
B = tk.Button(frame_right, text="删除当前节点", command=lambda: self.node_del_exact())
B.place(relx=0.1, rely=0.1 + y0, width=150, height=30)
if d.Nodes[curx][4] == 1:
text = '设为非必经节点'
else:
text = '设为必经节点'
B = tk.Button(frame_right, text=text, command=lambda: self.dominator(curx))
B.place(relx=0.1, rely=0.15 + y0, width=150, height=30)
B = tk.Button(frame_right, text="增加一个节点", command=lambda: self.node_add())
B.place(relx=0.1, rely=0.25 + y0, width=150, height=30)
B = tk.Button(frame_right, text="减少一个节点", command=lambda: self.node_del())
B.place(relx=0.1, rely=0.3 + y0, width=150, height=30)
def dominator(self, x):
d.Nodes[x][4] ^= 1
G.draw()
self.node_mark_display()
def node_mark(self, name):
if name >= len(d.Nodes):
self.node_404(name)
return
for node in d.Nodes:
if node[0] == name:
node[2] = 1
# -*- coding: utf-8 -*-
# Time : 2023/10/30 15:49
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : X3.py
from collections import Counter
···
class Solve ():
def node_dfs(self): # 遍历 深度优先算法
self.start = time.time() # 记录开始时间
self.way_sum = 0
self.ans.clear() # 初始化答案列表
E.edge_del_all(1) # 两点间仅保留距离最短路径
for edge in d.Edges: # 清空标记
edge[4] = False
i = 0 # 起始点
flag = [0] * len(d.Nodes) # 初始化已经过点
cur = i # 初始化起始点
flag[cur] = 1 # 将起始点标记为已经过
l = len(d.Nodes)
distances = [[math.inf for _ in range(l)]
for _ in range(l)]
result = d.node_coordinate(l)
for j in d.Edges: # 每一步选择当前最短的链接加到路径中去
if j[0] >= len(result):
break
else:
node[2] = 0
G.draw()
self.node_mark_display()
def node_del_exact(self):
if d.nodes_num <= 2:# 若删除节点以后节点过少,则直接返回并警告
tk.messagebox.askokcancel(title='错误', message='节点过少')
return
flag = 0
cur = -1
for node in d.Nodes:# 寻找当前选定的节点
if node[2] == 1:
cur = node[0]
flag = 1
if flag == 0:
tk.messagebox.askokcancel(title='错误', message='未选择节点')
return
d.nodes_num -= 1#节点数目减一
d.ang = 360 / d.nodes_num#重新计算圆心角
nodes = d.Nodes.copy()#复制节点
d.Nodes.clear()#清除Data中的节点
num = 0
for n in nodes:#逐个复制节点
if n[0] == cur:#若是删除的节点,则不复制
continue
n[0] = num#重新编号
rad = math.radians(num * d.ang)#计算当前角度
x = int(math.cos(rad) * d.R)#计算当前点x坐标相对
y = int(math.sin(rad) * d.R)#计算当前点y坐标相对
n[3] = (d.center[0] + x, d.center[1] + y)#计算绝对坐标
d.Nodes.append(n)#将当前点加入点集合中
num += 1
edges = d.Edges.copy()#将原有边集复制出来
d.Edges.clear()#删除Data中的边集
num = 0
for e in edges:#复制边
if e[1] == cur or e[2] == cur:#删除的边不复制
continue
if e[1] > cur:#修改边对应的点的编号
e[1] -= 1
if e[2] > cur:#修改边对应的点的编号
e[2] -= 1
e[0] = num#重新编号
d.Edges.append(e)#将边加入边集中
num += 1
G.draw()#重新绘图
self.node_mark_display()
def node_rename(self):
flag = 0
for node in d.Nodes:
if node[2] == 1:
cur = node
flag = 1
if flag == 1:
result = tkinter.simpledialog.askstring(title='修改节点标签', prompt='请输入修改后的标签:',
initialvalue=cur[1])
else:
tk.messagebox.askokcancel(title='错误', message='未选择节点')
return
if result:
cur[1] = result
G.draw()
self.node_mark_display()
def node_clear(self):
for node in d.Nodes:
node[2] = False
G.draw()
def node_add(self):
# 增加一个节点
nodes = len(d.Nodes) + 1
# 如果节点数目大于五,则将连接详细信息改为不显示
if nodes > 5:
d.edgeinfo = 0
self.node_init(nodes)
G.draw()
self.node_mark_display()
def node_set(self):
node = tkinter.simpledialog.askinteger(title='修改节点数目', prompt='请输入修改后的节点数目:',
initialvalue=str(len(d.Nodes)))
if node:
self.node_init(node)
G.draw()
def node_del(self):
if d.nodes_num <= 2:
tk.messagebox.askokcancel(title='错误', message='节点过少')
return
nodes = len(d.Nodes) - 1
if nodes < 6:
d.edgeinfo = 1
self.node_init(nodes)
G.draw()
self.node_mark_display()
def node_init(self, node):
if not node:
return
if d.source == 1:
d.data(node)
elif d.source == 2:
if node > 13:
tk.messagebox.askokcancel(title='错误', message='节点过多')
return
d.HEI_data(node)
else:
if node > 13:
tk.messagebox.askokcancel(title='错误', message='节点过多')
return
d.LIAO_data(node)
if node > 5:
d.edgeinfo = 0
else:
d.edgeinfo = 1
def graph_del(self):
global d
del d
def node_refresh(self):
nodes = len(d.Nodes)
self.node_init(nodes)
G.draw()
self.node_mark_display()
def node_404(self, name):
# 弹出对话框
tk.messagebox.askokcancel(title='错误', message='该节点不存在')
# print(result)
if j[6] < 99 and j[7] < 99:
distances[result[j[0]][0]][
result[j[0]][1]] = j[6]
distances[result[j[0]][1]][
result[j[0]][0]] = j[6]
cost, ways = self.dfs(distances)
print(self.way_sum)
self.ans = ways.copy()
if len(ways) != l + 1:
tk.messagebox.askokcancel(title='结果',
message='该图不存在dfs路径')
# print(ways)
for way in range(len(ways) - 1): # 标记一条路径
d.Edges[G.way_node_edge(ways[way],
ways[way + 1])][4] = True
self.end = time.time() # 记录结束时间
self.ans.clear()
return -1
for way in range(len(ways) - 1): # 标记一条路径
d.Edges[G.way_node_edge(ways[way],
ways[way + 1])][4] = True
tk.messagebox.askokcancel(title='结果',
message='dfs算法路径')
self.end = time.time() # 记录结束时间
def greedy(self, distances):
num_cities = len(distances)
visited = [False] * num_cities
path = [0] # 起始城市为0
visited[0] = True
for _ in range(num_cities - 1):
curr_city = path[-1]
min_distance = float('inf')
next_city = None
for city in range(num_cities):
if not visited[city] and distances[curr_city][city] \
< min_distance and distances[curr_city][
city] != 0:
min_distance = distances[curr_city][city]
next_city = city
self.way_sum += 1 # 遍历路径的数目加一
if next_city is not None:
path.append(next_city)
visited[next_city] = True
if distances[path[-1]][0] != np.inf:
path.append(0) # 回到起始城市形成闭合路径
# print(path)
return path
if __name__ == '__main__':
G.draw()
node = Node()
node.node_mark_display()
mainloop()
···编程[11.2]与编程[11.5]主函数
s. node_greedy () # 开始遍历搜索合法路径

1464
X4.py

File diff suppressed because it is too large Load Diff

1459
X4_1.py

File diff suppressed because it is too large Load Diff

1615
X4_2.py

File diff suppressed because it is too large Load Diff

1730
X4_3.py

File diff suppressed because it is too large Load Diff

1730
X4_4.py

File diff suppressed because it is too large Load Diff

@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
# Time : 2023/10/30 15:49
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : X5.py

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 997 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

@ -0,0 +1,36 @@
class Ways():
def way_change(self):
global entry3, entry4
value1 = entry3.get() # 获取第一个输入框的值
value2 = entry4.get() # 获取第二个输入框的值
try:
value1 = int(value1) # 将值转换为整数
value2 = int(value2) # 将值转换为整数
print("值1:", value1)
print("值2:", value2)
ways_list = [int(node[1]) for node in d.Nodes]
# 判断两点是否连接
if abs(value2) > 10 and abs(value1) > 10:
tk.messagebox.askokcancel(title='错误', message='请重新输入正确的编号!')
return
else:
if value1 < value2:
str_route = f'{value1}-{value2}'
else:
str_route = f'{value2}-{value1}'
no = 0
for item in d.Edges:
if str_route == item[5]:
no = G.node_edge(value1 - 1, value2 - 1)
if d.Edges[no][3] == 0:
tk.messagebox.askokcancel(title='提醒', message='当前路线不存在!')
return
top = creat_window(str_route + '路径参数修改') # 创建弹出窗口
distance_entry = create_input_box(top, "路程/公里1-99", d.Edges[no][6]) # 创建一个输入框,获取卷积核大小
time_entry = create_input_box(top, "时间/h1-99", d.Edges[no][7]) # 创建一个输入框,获取卷积步长
def get_input(): # 创建
···与前面way_add里get_input相似
button = tk.Button(top, text="获取信息", command=get_input)
button.pack()
except ValueError:
tk.messagebox.askokcancel(title='错误', message='请输入正确的城市编号!')

@ -0,0 +1,21 @@
# 导入aip模块这是一个来自百度AI平台的Python SDK可以用来调用百度NLP自然语言处理服务
from aip import AipNlp
# 定义一个名为address的函数它接受一个字符串参数addr默认为空字符串
def address(addr=''):
# 在这个函数中定义了APP_ID、API_KEY和SECRET_KEY三个变量这些变量是你在百度AI平台上申请的凭证
APP_ID = '41768293'
API_KEY = 'CAnsdV8e40GQtjhK4qHkucUO'
SECRET_KEY = 'jU1NbbnwrhTahngr2p3cz8p2EIAa8zWj'
# 使用凭证创建一个AipNlp的客户端对象这个对象会用来发送请求到百度AI平台
client = AipNlp(APP_ID, API_KEY, SECRET_KEY)
""" 调用词法分析 """
# 调用客户端对象的address方法将参数addr发送到百度AI平台进行地址识别返回的结果保存在变量re中
re = client.address(addr)
# 返回识别的结果
return re
# 调用address函数参数为你要识别的具体地址并将返回的结果打印出来
print(address('海南省三亚市吉阳区迎宾大道学院路三亚学院'))

@ -1,248 +1,61 @@
# -*- encoding: utf-8 -*-
from NODE import *
from SOLVE import *
from EDGE import *
from WAYS import *
N = Node()
E = Edge()
W = Ways()
mode = tk.IntVar(value=1)
# 目前的操作状态:
# 1为节点操作
# 2为链接操作
# 3为路径操作
# 默认为1
RIGHT = -1
B = tk.Button(frame, text="修改", command=lambda: N.node_set())
B.place(x=180, y=10, width=50, height=30)
def left1(event):
# 查找鼠标左键按下时位置是否在某个节点内
n = -1
for node in d.Nodes:
if dir2([event.x, event.y], [node[3][0], node[3][1]]) < 20 * 20:
n = node[0]
# n为点击的节点若没有则为-1
m = mode.get() # 查看现在操作类型
if m == 1 and not n == -1:
# 节点操作
N.node_mark(n)
elif m == 2 and not n == -1:
# 链接操作
if len(E.mark) == 0:
E.mark.append(n)
E.node_mark1(E.mark[0])
elif len(E.mark) == 1:
E.mark.append(n)
E.node_mark1(E.mark[0])
E.node_mark2(E.mark[1])
elif not n == E.mark[1]:
n1 = E.mark[1]
E.mark.clear()
E.mark.append(n1)
E.mark.append(n)
E.node_mark1(E.mark[0])
E.node_mark2(E.mark[1])
# 路径操作
elif m == 3 and not n == -1:
W.user_way_add(n)
# 自动判断操作
elif m == 4 and not n == -1:
if len(solve.mark) == 0:
solve.mark.append(n)
solve.node_mark1(solve.mark[0])
elif len(solve.mark) == 1:
solve.mark.append(n)
solve.node_mark1(solve.mark[0])
solve.node_mark2(solve.mark[1])
elif not n == solve.mark[1]:
n1 = solve.mark[1]
solve.mark.clear()
solve.mark.append(n1)
solve.mark.append(n)
solve.node_mark1(solve.mark[0])
solve.node_mark2(solve.mark[1])
def onRightButtonUp(event):
global RIGHT
# 查找鼠标右键按下时位置是否在某个节点内
n = -1
for node in d.Nodes:
if dir2([event.x, event.y], [node[3][0], node[3][1]]) < 20 * 20:
n = node[0]
if n == -1:
menu.post(event.x_root, event.y_root)
else:
RIGHT = n
menu_node.post(event.x_root, event.y_root)
# 右键菜单
def m_node():
mode.set(1)
W.clear()
N.node_mark_display()
def m_edge():
mode.set(2)
W.clear()
E.edge_mark_display()
def m_ways():
mode.set(3)
W.user_way_clear()
W.way_mark_display()
def m_info():
d.edgeinfo ^= 1
G.draw()
def m_solve():
W.clear()
mode.set(4)
solve.Solve_display()
def graph_init():
nodes = random.randint(4, 10)
N.node_init(nodes)
G.draw()
N.node_mark_display()
def sourc_set(num):
W.clear()
d.source = num
N.node_init(nodes)
G.draw()
def node_del(num):
N.node_mark(num)
N.node_del_exact()
def node_name(num):
N.node_mark(num)
N.node_rename()
def node_condition(num):
d.Nodes[num][4] ^= 1
G.draw()
menu = tk.Menu(root, tearoff=0)
menu.add_command(label='节点操作', command=m_node)
menu.add_command(label='连接操作', command=m_edge)
menu.add_command(label='路径操作', command=m_ways)
menu.add_command(label='显示/隐藏链接信息', command=m_info)
menu.add_command(label='自动判断相关', command=m_solve)
fmenu1 = Menu(menu, tearoff=False)
fmenu1.add_command(label='使用模拟数据', command=lambda: sourc_set(1))
fmenu1.add_command(label='使用黑龙江省数据', command=lambda: sourc_set(2))
fmenu1.add_command(label='使用辽宁省数据', command=lambda: sourc_set(3))
menu.add_cascade(label="切换数据源", menu=fmenu1)
menu_node = tk.Menu(root, tearoff=0)
menu_node.add_command(label='删除节点', command=lambda: node_del(RIGHT))
menu_node.add_command(label='切换必经/非必经', command=lambda: node_condition(RIGHT))
menu_node.add_command(label='重命名节点', command=lambda: node_name(RIGHT))
# menu_node.add_command(label='显示/隐藏链接信息', command=m_info)
cv.bind('<Button-1>', left1)
cv.bind('<ButtonRelease-3>', onRightButtonUp)
# 释放右键时打开菜单
def auto_opera_mu(menu: tk.Menu):
"""TSP问题自动生成与自动求解相关"""
menu_node = Menu(menu, tearoff=False)
menu_node.add_command(label="自动随机产生一个TSP问题", command=lambda: graph_init())
menu_node.add_command(label="重新生成", command=lambda: N.node_refresh())
menu_node.add_command(label="自动求解最优路径-遍历", command=lambda: solve.dfs_panel())
menu_node.add_command(label="自动求解优化路径-贪心", command=lambda: solve.greedy_panel())
menu_node.add_command(label="检查是否存在路径", command=lambda: solve.check())
# 在主目录菜单上新增"文件"选项并通过menu参数与下拉菜单绑定
menu.add_cascade(label="TSP问题自动生成与自动求解相关", menu=menu_node)
def node_opera_mu(menu: tk.Menu):
"""节点操作"""
# fmenu1 = Menu(menu, tearoff=False)
# for i in range(10):
# fmenu1.add_command(label='选择节点 ' + str(i + 1), command=lambda num=i: node_mark(num))
menu_node = Menu(menu, tearoff=False)
menu_node.add_command(label="添加一个节点", command=lambda: N.node_add())
menu_node.add_command(label="删除一个节点", command=lambda: N.node_del())
# menu_node.add_cascade(label="选择一个节点", menu=fmenu1)
menu_node.add_command(label="选择一个节点", command=lambda: N.node_mark_display())
# menu_node.add_command(label="停止标记一个节点", command=lambda: node_mark_display1())
# menu_node.add_command(label="设置节点标签", command=lambda:node_rename())
# 在主目录菜单上新增"文件"选项并通过menu参数与下拉菜单绑定
menu.add_cascade(label="节点操作", menu=menu_node)
def edge_opera_mu(menu: tk.Menu):
"""连接操作"""
# fmenu1 = Menu(menu, tearoff=False)
# for i in range(10):
# fmenu1.add_command(label='选择另一个节点 ' + str(i + 1), command=lambda num=i: node_mark2(num))
#
menu_node = Menu(menu, tearoff=False)
# menu_node.add_cascade(label="选择另一个节点", menu=fmenu1)
menu_node.add_command(label="选择一个连接", command=lambda: E.edge_mark_display())
# menu_node.add_command(label="建立一个连接",command=lambda :edge_add())
menu_node.add_command(label="删除所有连接", command=lambda: E.edge_delall())
menu_node.add_command(label="删除所有多余连接", command=lambda: E.newedge_del_all(1))
# menu_node.add_command(label="设置连接标签", command=lambda: edge_rename())
# 在主目录菜单上新增"文件"选项并通过menu参数与下拉菜单绑定
menu.add_cascade(label="连接操作", menu=menu_node)
def path_opera_mu(menu: tk.Menu):
"""路径操作"""
menu_node = Menu(menu, tearoff=False)
menu_node.add_command(label="开始标记路径", command=lambda: W.way_mark_display())
menu_node.add_command(label="撤销一步路径", command=lambda: W.user_way_del())
menu_node.add_command(label="取消所有路径标记", command=lambda: W.user_way_clear())
# 在主目录菜单上新增"文件"选项并通过menu参数与下拉菜单绑定
menu.add_cascade(label="路径操作", menu=menu_node, )
auto_opera_mu(main_menu)
node_opera_mu(main_menu)
edge_opera_mu(main_menu)
path_opera_mu(main_menu)
def main():
G = Graph()
G.draw()
sourc_set(2)
mainloop()
if __name__ == '__main__':
main()
import sys
import numpy as np
def tsp_nearest_neighbor1(distances):
num_cities = len(distances)
visited = [False] * num_cities
path = [0] # 起始城市为0
visited[0] = True
for _ in range(num_cities - 1):
curr_city = path[-1]
min_distance = sys.maxsize
nearest_city = None
for city in range(num_cities):
if not visited[city] and distances[curr_city][city] < min_distance and distances[curr_city][city] != 0:
min_distance = distances[curr_city][city]
nearest_city = city
if nearest_city is not None:
path.append(nearest_city)
visited[nearest_city] = True
path.append(0) # 回到起始城市形成闭合路径
return path
def tsp_nearest_neighbor(distances):
num_cities = len(distances)
visited = [False] * num_cities
path = [0] # 起始城市为0
visited[0] = True
for _ in range(num_cities - 1):
curr_city = path[-1]
min_distance = sys.maxsize
nearest_city = None
for city in range(num_cities):
if not visited[city] and distances[curr_city][city] < min_distance and distances[curr_city][city] != 0:
min_distance = distances[curr_city][city]
nearest_city = city
if nearest_city is not None:
path.append(nearest_city)
visited[nearest_city] = True
path.append(0) # 回到起始城市形成闭合路径
return path
# 示例用法
distances = np.array([
[np.inf, 50, 99, np.inf, 64, np.inf],
[50, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
path = tsp_nearest_neighbor1(distances)
print(path)

@ -0,0 +1,49 @@
import numpy as np
def tsp_dp(distances):
n = len(distances)
dp = np.full((1 << n, n), np.inf)
path = np.zeros((1 << n, n), dtype=int)
for i in range(n):
dp[1 << i][i] = 0
for S in range(1, 1 << n):
for j in range(n):
if not (S & (1 << j)):
continue
for k in range(n):
if k == j or not (S & (1 << k)):
continue
if dp[S][j] > dp[S - (1 << j)][k] + distances[k][j]:
dp[S][j] = dp[S - (1 << j)][k] + distances[k][j]
path[S][j] = k
final_path = []
S = (1 << n) - 1
j = 0
while S:
final_path.append(j)
k = path[S][j]
S -= 1 << j
j = k
final_path.append(0)
ans = float('inf')
for j in range(n): # 枚举所有结束点
if distances[j][0] != np.inf: # 如果结束点j与起点0相连
ans = min(ans, dp[(1 << n) - 1][j] + distances[j][0])
return ans, final_path
# 示例使用
distances = np.array([
[np.inf, 50, 99, np.inf, 64, np.inf],
[50, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
min_cost, min_path = tsp_dp(distances)
print("Minimum cost:", min_cost)
print("Minimum path:", min_path)

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
# Time : 2023/11/3 17:42
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : Prin.py
import numpy as np
def prim_exists_path(distances):
num_cities = distances.shape[0]
visited = set()
pq = []
start_node = 0
visited.add(start_node)
for neighbor in range(num_cities):
if neighbor != start_node and np.isfinite(distances[start_node, neighbor]):
pq.append((distances[start_node, neighbor], start_node, neighbor))
pq.sort(key=lambda x: x[0])
while pq:
weight, node1, node2 = pq.pop(0)
if node2 not in visited:
visited.add(node2)
for neighbor in range(num_cities):
if neighbor != node2 and np.isfinite(distances[node2, neighbor]):
pq.append((distances[node2, neighbor], node2, neighbor))
pq.sort(key=lambda x: x[0])
return len(visited) == num_cities
distances = np.array([
[np.inf, 50, 99, np.inf, 64, np.inf],
[50, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
print(prim_exists_path(distances))

@ -0,0 +1,76 @@
import random
def initialize_population(num_points, pop_size):
population = []
for _ in range(pop_size):
individual = list(range(num_points))
random.shuffle(individual)
population.append(individual)
return population
def evaluate_fitness(individual, distances):
fitness = 0
num_points = len(individual)
for i in range(num_points):
city1 = individual[i]
city2 = individual[(i + 1) % num_points]
fitness += distances[city1][city2]
return fitness
def crossover(parent1, parent2):
child = [-1] * len(parent1)
start_idx = random.randint(0, len(parent1)-1)
end_idx = random.randint(start_idx+1, len(parent1))
child[start_idx:end_idx] = parent1[start_idx:end_idx]
for city in parent2:
if city not in child:
for i in range(len(child)):
if child[i] == -1:
child[i] = city
break
return child
def mutate(individual):
idx1, idx2 = random.sample(range(len(individual)), 2)
individual[idx1], individual[idx2] = individual[idx2], individual[idx1]
def genetic_algorithm(distances, pop_size, num_generations):
num_points = len(distances)
population = initialize_population(num_points, pop_size)
for generation in range(num_generations):
population_fitness = []
for individual in population:
fitness = evaluate_fitness(individual, distances)
population_fitness.append((individual, fitness))
population_fitness.sort(key=lambda x: x[1]) # 按适应度排序
elite_individual = population_fitness[0][0]
new_population = [elite_individual]
while len(new_population) < pop_size:
parent1, parent2 = random.choices(population_fitness, k=2)
child = crossover(parent1[0], parent2[0])
mutate(child)
new_population.append(child)
population = new_population
best_individual = population_fitness[0][0]
return best_individual
# 示例使用
# distances为距离矩阵
distances = [
[0, 50, 99, 0, 64, 0],
[50, 0, 12, 45, 74, 13],
[99, 12, 0, 25, 0, 61],
[0, 45, 25, 0, 45, 47],
[64, 74, 0, 45, 0, 0],
[0, 13, 61, 47, 0, 0]
]
population_size = 100
num_generations = 1000
best_solution = genetic_algorithm(distances, population_size, num_generations)
print(best_solution)

@ -0,0 +1,46 @@
import numpy as np
inf = float('inf')
distances = np.array([
[inf, 72, inf, inf, 81, 67],
[72, inf, 26, inf, 61, inf],
[inf, 26, inf, 53, 97, inf],
[inf, inf, 53, inf, inf, inf],
[81, 61, 97, inf, inf, 38],
[67, inf, inf, inf, 38, inf]
])
def find_cycles(start, distances):
n = len(distances)
path = [start]
cycles = []
def is_valid(node, position):
if distances[path[position - 1]][node] == inf:
return False
if node in path:
return False
return True
def find_paths(node):
for next_node in range(n):
if is_valid(next_node, len(path)):
path.append(next_node)
if len(path) < n:
find_paths(next_node)
elif len(path) == n and distances[path[-1]][start] != inf:
cycles.append(path.copy())
path.pop()
find_paths(start)
return cycles
all_cycles = find_cycles(0, distances)
if all_cycles:
print("经过全部节点能返回起点的回路的全部路径为:")
for cycle in all_cycles:
print(cycle + [cycle[0]]) # 添加起点以形成完整的回路
else:
print("不存在经过全部节点能返回起点的回路")

@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
# Time : 2023/11/9 11:26
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : demo11.py
import os
# 遍历指定文件夹
def rename_files(folder_path):
for root, dirs, files in os.walk(folder_path):
for file in files:
# 检查文件类型是否为图片类型(这里使用了简单的判断方式)
if file.endswith('.jpg') or file.endswith('.png'):
# 获取当前文件所在的子文件夹名称
subdir_name = os.path.basename(root)
# 组合新的文件名,添加子文件夹名称前缀
new_file_name = subdir_name + '_' + file
# 使用 os.rename() 方法来重命名文件
os.rename(os.path.join(root, file), os.path.join(root, new_file_name))
# 调用函数来重命名文件
rename_files('D:/weixin/WeChat Files/wxid_f2yvfdxbyuag22/FileStorage/File/2023-11/球/')

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Time : 2023/11/9 11:28
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : demo12.py
import os
import shutil
# 遍历指定文件夹并复制图片文件到新的文件夹
def copy_images(folder_path, target_folder_path):
# 创建目标文件夹(如果它不存在)
if not os.path.exists(target_folder_path):
os.makedirs(target_folder_path)
for root, dirs, files in os.walk(folder_path):
for file in files:
# 检查文件类型是否为图片类型(这里使用了简单的判断方式)
if file.endswith('.jpg') or file.endswith('.png'):
# 构造源文件的完整路径
source_file_path = os.path.join(root, file)
# 构造目标文件的完整路径
target_file_path = os.path.join(target_folder_path, file)
# 使用 shutil 模块的 copy2() 函数复制文件(保留源文件的元数据)
shutil.copy2(source_file_path, target_file_path)
# 调用函数来复制图片文件
copy_images('D:/weixin/WeChat Files/wxid_f2yvfdxbyuag22/FileStorage/File/2023-11/球/', 'K:/工作/traveler/background/')

@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
# Time : 2023/11/9 11:54
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : demo13.py
import os
# 读取文件夹中的图像文件名到列表
def get_image_filenames(folder_path):
image_filenames = []
for file_name in os.listdir(folder_path):
# 检查文件类型是否为图像类型(这里使用了简单的判断方式)
if file_name.endswith('.jpg') or file_name.endswith('.png'):
# 将文件名添加到列表中
image_filenames.append(file_name)
return image_filenames
# 调用函数来获取图像文件列表
image_files = get_image_filenames('K:/工作/traveler/background/')
print(image_files)

@ -0,0 +1,106 @@
import numpy as np
class AntColonyOptimization:
def __init__(self, distances, num_ants=10, num_iterations=100, alpha=1, beta=1, evaporation=0.5, q0=0.9):
self.distances = distances
self.num_ants = num_ants
self.num_iterations = num_iterations
self.alpha = alpha
self.beta = beta
self.evaporation = evaporation
self.q0 = q0
def optimize(self):
num_cities = len(self.distances)
pheromone = np.ones((num_cities, num_cities))
best_path = None
best_length = float('inf')
for _ in range(self.num_iterations):
paths = []
lengths = []
for _ in range(self.num_ants):
path = self.construct_path(pheromone)
length = self.calculate_length(path)
paths.append(path)
lengths.append(length)
if length < best_length:
best_length = length
best_path = path
self.update_pheromone(pheromone, paths, lengths)
return best_path
def construct_path(self, pheromone):
num_cities = len(pheromone)
path = [0] # 起始城市为0
visited = np.zeros(num_cities, dtype=bool)
visited[0] = True
for _ in range(num_cities - 1):
probs = self.calculate_probs(pheromone, path[-1], visited)
next_city = self.choose_next_city(probs)
path.append(next_city)
visited[next_city] = True
return path
def calculate_probs(self, pheromone, curr_city, visited):
num_cities = len(pheromone)
probs = np.zeros(num_cities)
denominator = 0
for city in range(num_cities):
if not visited[city]:
denominator += pheromone[curr_city, city] ** self.alpha + (1.0 / self.distances[curr_city, city]) ** self.beta
for city in range(num_cities):
if not visited[city]:
numerator = pheromone[curr_city, city] ** self.alpha + (1.0 / self.distances[curr_city, city]) ** self.beta
probs[city] = numerator / denominator
return probs
def choose_next_city(self, probs):
q = np.random.rand()
if q < self.q0:
next_city = np.argmax(probs)
else:
next_city = np.random.choice(len(probs), p=probs)
return next_city
def calculate_length(self, path):
length = 0
for i in range(len(path) - 1):
length += self.distances[path[i], path[i+1]]
return length
def update_pheromone(self, pheromone, paths, lengths):
pheromone *= self.evaporation
for i, path in enumerate(paths):
for j in range(len(path) - 1):
city1 = path[j]
city2 = path[j+1]
pheromone[city1, city2] += 1.0 / lengths[i]
pheromone[city2, city1] += 1.0 / lengths[i]
distances = np.array([
[np.inf, 50, 99, np.inf, 64, np.inf],
[50, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
aco = AntColonyOptimization(distances)
best_path = aco.optimize()
print(best_path)

@ -0,0 +1,66 @@
import numpy as np
def tsp_backtracking(distances):
num_cities = len(distances)
path = [0] # 起始城市为0
visited = [False] * num_cities
visited[0] = True
min_distance = float('inf')
shortest_path = None
def backtrack(curr_city, curr_distance, visited, path):
nonlocal min_distance, shortest_path
if len(path) == num_cities:
# 到达所有城市,更新最短路径
if curr_distance + distances[curr_city][0] < min_distance:
min_distance = curr_distance + distances[curr_city][0]
shortest_path = path + [0]
else:
for next_city in range(num_cities):
if not visited[next_city]:
# 选择下一个未访问的城市
visited[next_city] = True
path.append(next_city)
new_distance = curr_distance + distances[curr_city][next_city]
# 剪枝条件:当前路径已经大于最短路径,不继续搜索
if new_distance < min_distance:
backtrack(next_city, new_distance, visited, path)
# 回溯
visited[next_city] = False
path.pop()
backtrack(0, 0, visited, path)
return shortest_path
# 示例用法
# distances = np.array([
# [np.inf, 50, 99, np.inf, 64, np.inf],
# [50, np.inf, 12, 45, 74, 13],
# [99, 12, np.inf, 25, np.inf, 61],
# [np.inf, 45, 25, np.inf, 45, 47],
# [64, 74, np.inf, 45, np.inf, np.inf],
# [np.inf, 13, 61, 47, np.inf, np.inf]
# ])
# inf = np.inf
# distances = np.array(
# [[inf, 69, 48, inf, 41, 78],
# [69, inf, 48, 53, 91, inf],
# [48, 48, inf, 19, 86, inf],
# [inf, 53, 19, inf, 96, 10],
# [41, 91, 86, 96, inf, inf],
# [78, inf, inf, 10, inf, inf]]
# )
inf = float('inf')
distances = np.array([
[inf, 72, inf, inf, 81, 67],
[72, inf, 26, inf, 61, inf],
[inf, 26, inf, 53, 97, inf],
[inf, inf, 53, inf, inf, inf],
[81, 61, 97, inf, inf, 38],
[67, inf, inf, inf, 38, inf]
])
path = tsp_backtracking(distances)
if path:
print(path)
else:
print('不存在')

@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
# Time : 2023/10/31 11:01
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : demo5.py
import numpy as np
inf = float('inf')
distances = np.array([[inf, 71, 88, 28, 67, inf], [71, inf, inf, inf, 51, 98], [88, inf, inf, 70, inf, inf], [28, inf, 70, inf, 90, 75], [67, 51, inf, 90, inf, inf], [inf, 98, inf, 75, inf, inf]])
def find_hamiltonian_cycles(start, distances):
n = len(distances)
path = [start]
cycles = []
def is_valid(node, position):
if distances[path[position - 1]][node] == inf:
return False
if node in path:
return False
return True
def find_paths(node):
for next_node in range(n):
if is_valid(next_node, len(path)):
path.append(next_node)
if len(path) < n:
find_paths(next_node)
elif len(path) == n and distances[path[-1]][start] != inf:
cycles.append(path + [start])
path.pop()
find_paths(start)
return cycles
all_cycles = find_hamiltonian_cycles(0, distances)
if all_cycles:
print("经过全部节点能返回起点的回路的全部路径为:")
for cycle in all_cycles:
print(cycle) # 输出所有回路路径
else:
print("不存在经过全部节点能返回起点的回路")

@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
# Time : 2023/11/3 17:21
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : demo6.py
import sys
import itertools
import numpy as np
def tsp_dp(distances):
n = len(distances)
dp = [[sys.maxsize] * n for _ in range(1 << n)]
dp[1][0] = 0
for mask in range(1, 1 << n):
for current in range(n):
if mask & (1 << current):
for previous in range(n):
if previous != current and mask & (1 << previous):
dp[mask][current] = min(dp[mask][current], dp[mask ^ (1 << current)][previous] + distances[previous][current])
shortest_path = sys.maxsize
end_mask = (1 << n) - 1
last_city = -1
for i in range(1, n):
if shortest_path > dp[end_mask][i] + distances[i][0]:
shortest_path = dp[end_mask][i] + distances[i][0]
last_city = i
path = []
mask = end_mask
while last_city >= 0:
path.append(last_city)
new_mask = mask ^ (1 << last_city)
last_city = -1
for i in range(n):
if new_mask & (1 << i):
if last_city == -1 or dp[mask][last_city] + distances[last_city][i] == dp[mask][i]:
last_city = i
mask = new_mask
path.append(0)
path.reverse()
return shortest_path, path
#
# # 测试代码
# distances = [
# [0, 2, 9, 10],
# [1, 0, 6, 4],
# [15, 7, 0, 8],
# [6, 3, 12, 0]
# ]
# 测试代码
distances = np.array([
[np.inf, 80, 99, np.inf, 64, np.inf],
[80, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
shortest_path, path = tsp_dp(distances)
print("最短路径长度为:", shortest_path)
print("最短路径为:", path)

@ -0,0 +1,119 @@
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from operator import eq
flag = True
def get_paragraph_shading(p):
"""
Get paragraph`s shading
Usage:
get_paragraph_shading(paragraph)
"""
p_pr = p._p.get_or_add_pPr() # 获取段落的pPr
# print(p_pr)
p_shd = p_pr.first_child_found_in("w:shd") # 找到 'w:shd' 标签
# 如果不存在,就创建
if p_shd is None:
p_shd = OxmlElement('w:shd')
p_pr.append(p_shd)
# 获取各属性的值
val = p_shd.get(qn('w:val'))
# color = p_shd.get(qn('w:color'))
fill = p_shd.get(qn('w:fill'))
print([val, fill])
return [val, fill]
def get_paragraph_boders(p):
"""
Get paragraph`s boders
Usage:
get_paragraph_boders(paragraph)
"""
p_pr = p._p.get_or_add_pPr() # 获取段落的pPr
p_borders = p_pr.first_child_found_in("w:pBdr") # 找到 'p_borders' 标签
# 如果不存在,就创建
if p_borders is None:
p_borders = OxmlElement('w:pBdr')
p_pr.append(p_borders)
# 获取各属性的值
borders = []
for edge in ('left', 'top', 'right', 'bottom'):
element = p_borders.find(qn('w:{}'.format(edge)))
if element is None:
element = OxmlElement('w:{}'.format(edge))
p_borders.append(element)
border = []
for key in ["sz", "val", "color"]:
temp = str(element.get(qn('w:{}'.format(key))))
if temp == 'none' or temp == '0' or temp == 'auto' or temp == 'NONE':
temp = 'None'
border.append(temp)
borders.append(border)
return borders
def get_text_borders(p):
t_pr = p.runs[0].element.rPr
t_bor = t_pr.first_child_found_in("w:bdr") # 找到 'w:bdr' 标签
# 如果不存在,就创建
if t_bor is None:
t_bor = OxmlElement('w:bdr')
t_pr.append(t_bor)
# # 获取各属性的值
val = t_bor.get(qn('w:val'))
color = t_bor.get(qn('w:color'))
sz = t_bor.get(qn('w:sz'))
return [val, sz, color]
def Comp(name1, name2):
"""
Compare the diferences of two files
Usage:
Comp(file_name1, file_name2)
"""
global flag
ff = 'K:/工作/traveler/test/'
# s = Document(name1)
# t = Document(name2)
s = Document(ff + name1)
t = Document(ff + name2)
# 获取段落
x = s.paragraphs
y = t.paragraphs
l = len(x)
for i in range(l-1):
s_shd = get_paragraph_shading(x[i])
t_shd = get_paragraph_shading(y[i])
s_border = get_paragraph_boders(x[i])
t_border = get_paragraph_boders(y[i])
if not eq(s_shd, t_shd):
print('效果对比出错,问题:',s_shd,'应该修改为:',t_shd)
print(1)
flag = False
break
if not eq(s_border, t_border):
print(1)
print('效果对比出错,问题:',s_border,'应该修改为:',t_border)
flag = False
break
# 判断标题的文字边框
if not eq(get_text_borders(x[0]), get_text_borders(y[0])):
print('文字边框设置出错,问题:',get_text_borders(x[0]),'应该修改为:',get_text_borders(y[0]))
flag = False
try:
Comp('中国共产党党史.docx', '美化文档.docx')
if flag:
print('Accepted!')
else:
print('文件内容错误,请调整后重试!')
except Exception as e:
print(e)
print('请按步骤创建、操作文本后重试!')

@ -0,0 +1,30 @@
import numpy as np
import networkx as nx
inf = float('inf')
def find_hamiltonian_cycles(distances):
num_nodes = distances.shape[0]
graph = nx.DiGraph()
for i in range(num_nodes):
for j in range(num_nodes):
if distances[i][j] != inf:
graph.add_edge(i, j, weight=distances[i][j])
hamiltonian_cycles = list(nx.simple_cycles(graph))
hamiltonian_cycles = [cycle + [cycle[0]] for cycle in hamiltonian_cycles if len(cycle) == num_nodes - 1]
return hamiltonian_cycles
# distances = np.array([[inf, 69, 48, inf, 41, 78], [69, inf, 48, 53, 91, inf], [48, 48, inf, 19, 86, inf], [inf, 53, 19, inf, 96, 10], [41, 91, 86, 96, inf, inf], [78, inf, inf, 10, inf, inf]])
distances = np.array([[inf, 94, 67, 65, inf], [94, inf, inf, 41, inf], [67, inf, inf, inf, 65], [65, 41, inf, inf, 54], [inf, inf, 65, 54, inf]])
all_hamiltonian_cycles = find_hamiltonian_cycles(distances)
if all_hamiltonian_cycles:
print("存在的哈密尔顿回路路径为:")
for cycle in all_hamiltonian_cycles:
print(cycle)
else:
print("不存在哈密尔顿回路")

@ -0,0 +1,42 @@
import numpy as np
inf = float('inf')
def find_all_cycles(distances):
num_nodes = distances.shape[0]
visited = [False] * num_nodes
cycles = []
def dfs(node, start, path):
visited[node] = True
for neighbor in range(num_nodes):
if distances[node, neighbor] != inf:
if neighbor == start and len(path) > 1:
cycles.append(path + [start])
elif not visited[neighbor]:
dfs(neighbor, start, path + [neighbor])
visited[node] = False
for start_node in range(num_nodes):
dfs(start_node, start_node, [start_node])
return cycles
distances = np.array([
[inf, inf, 21, inf, 53],
[inf, inf, 77, 84, 93],
[21, 77, inf, inf, 53],
[inf, 84, inf, inf, inf],
[53, 93, 53, inf, inf]
])
all_cycles = find_all_cycles(distances)
if all_cycles:
print("存在的回路路径为:")
for cycle in all_cycles:
print(cycle)
else:
print("不存在回路")

@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
# Time : 2023/11/3 17:43
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : dfs.py
import numpy as np
def dfs_exists_path(distances):
num_cities = distances.shape[0]
visited = set()
start_node = 0
def dfs(node):
visited.add(node)
for neighbor in range(num_cities):
if neighbor != node and neighbor not in visited and np.isfinite(distances[node, neighbor]):
dfs(neighbor)
dfs(start_node)
return len(visited) == num_cities
def exists_path_without_inf(distances):
# Check if there are any infinite distances
if np.any(np.isinf(distances)):
return False
# Set the infinite distances to a large value
max_distance = np.max(distances) + 1
distances[np.isinf(distances)] = max_distance
# Use DFS to check if there exists a path
return dfs_exists_path(distances)
distances = np.array([
[np.inf, 50, 99, np.inf, 64, np.inf],
[50, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
print(exists_path_without_inf(distances))

@ -0,0 +1,53 @@
import numpy as np
def dfs_tsp(graph, start, current, path, visited, cost, min_cost, min_path):
if len(path) == len(graph) and graph[current][start] != np.inf:
path.append(start)
cost += graph[current][start]
if cost < min_cost[0]:
min_cost[0] = cost
min_path[0] = path.copy()
path.pop()
cost -= graph[current][start]
return
for next_node in range(len(graph)):
if graph[current][next_node] != np.inf and not visited[next_node]:
visited[next_node] = True
path.append(next_node)
cost += graph[current][next_node]
dfs_tsp(graph, start, next_node, path, visited, cost, min_cost, min_path)
visited[next_node] = False
path.pop()
cost -= graph[current][next_node]
def tsp_dfs(graph):
n = len(graph)
min_cost = [float('inf')]
min_path = [[]]
for start_node in range(n):
visited = [False] * n
path = [start_node]
cost = 0
visited[start_node] = True
dfs_tsp(graph, start_node, start_node, path, visited, cost, min_cost, min_path)
return min_cost[0], min_path[0]
# 示例使用
distances = np.array([
[np.inf, 50, 99, np.inf, 64, np.inf],
[50, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
min_cost, min_path = tsp_dfs(distances)
print("Minimum cost:", min_cost)
print("Minimum path:", min_path)

@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
# Time : 2023/10/31 10:22
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : greedy.py
import numpy as np
def tsp_greedy(distances):
num_cities = len(distances)
visited = [False] * num_cities
path = [0] # 起始城市为0
visited[0] = True
for _ in range(num_cities - 1):
curr_city = path[-1]
min_distance = float('inf')
next_city = None
for city in range(num_cities):
if not visited[city] and distances[curr_city][city] < min_distance and distances[curr_city][city] != 0:
min_distance = distances[curr_city][city]
next_city = city
if next_city is not None:
path.append(next_city)
visited[next_city] = True
if distances[path[-1]][0] != np.inf:
path.append(0) # 回到起始城市形成闭合路径
return path
distances = np.array([
[np.inf, 80, 99, np.inf, 64, np.inf],
[80, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
path = tsp_greedy(distances)
if len(path) == 6:
print('贪心算法路径:')
print(path)
else:
print('未找到!')
Loading…
Cancel
Save