@ -0,0 +1,6 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# Time : 2023/10/30 15:49
|
||||||
|
# Author : lirunsheng
|
||||||
|
# User : l'r's
|
||||||
|
# Software: PyCharm
|
||||||
|
# File : X1.py
|
@ -0,0 +1,6 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# Time : 2023/10/30 15:49
|
||||||
|
# Author : lirunsheng
|
||||||
|
# User : l'r's
|
||||||
|
# Software: PyCharm
|
||||||
|
# File : X5.py
|
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.8 KiB |
After Width: | Height: | Size: 4.3 KiB |
After Width: | Height: | Size: 4.4 KiB |
After Width: | Height: | Size: 4.5 KiB |
After Width: | Height: | Size: 4.1 KiB |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.7 KiB |
After Width: | Height: | Size: 4.3 KiB |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.8 KiB |
After Width: | Height: | Size: 4.3 KiB |
After Width: | Height: | Size: 4.5 KiB |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.1 KiB |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.7 KiB |
After Width: | Height: | Size: 4.3 KiB |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.8 KiB |
After Width: | Height: | Size: 4.3 KiB |
After Width: | Height: | Size: 4.5 KiB |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.2 KiB |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.8 KiB |
After Width: | Height: | Size: 4.3 KiB |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 4.8 KiB |
After Width: | Height: | Size: 4.3 KiB |
After Width: | Height: | Size: 2.1 KiB |
After Width: | Height: | Size: 2.5 KiB |
After Width: | Height: | Size: 3.4 KiB |
After Width: | Height: | Size: 3.3 KiB |
After Width: | Height: | Size: 1.7 KiB |
After Width: | Height: | Size: 2.1 KiB |
After Width: | Height: | Size: 1.4 KiB |
After Width: | Height: | Size: 1.3 KiB |
After Width: | Height: | Size: 1.5 KiB |
After Width: | Height: | Size: 2.0 KiB |
After Width: | Height: | Size: 3.2 KiB |
After Width: | Height: | Size: 997 B |
After Width: | Height: | Size: 3.2 KiB |
After Width: | Height: | Size: 1.2 KiB |
After Width: | Height: | Size: 2.2 KiB |
After Width: | Height: | Size: 2.2 KiB |
After Width: | Height: | Size: 2.1 KiB |
After Width: | Height: | Size: 4.8 KiB |
After Width: | Height: | Size: 15 KiB |
After Width: | Height: | Size: 91 KiB |
@ -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('未找到!')
|