from enum import Enum
defmodify_dict(func):defwrapper(input_dict):
modified_dict ={}for key, value in input_dict.items():
modified_key, modified_value = func(key, value)
modified_dict[modified_key]= modified_value
return modified_dict
return wrapper
@modify_dictdefadd_quotation_marks_to_keys(key, value):return"\""+ key +'\"', value
classPosition(Enum):
BEFORE ='before'
AFTER ='after'
BOTH ='both'defadd_symbol_to_keys_except_last(input_dict, symbol, position=Position.AFTER):
result_dict ={}
modified_dict = add_quotation_marks_to_keys(input_dict)
keys =list(modified_dict.keys())
last_key = keys[-1]for key, value in modified_dict.items():if key != last_key:if position == Position.BEFORE:
modified_key = symbol + key
elif position == Position.AFTER:
modified_key = key + symbol
elif position == Position.BOTH:
modified_key = symbol + key + symbol
else:raise ValueError("Position must be either 'before' or 'after'.")else:
modified_key = key
result_dict[modified_key]= value
return result_dict
# Example usage:
original_dict ={"key1":1,"key2":2,"key3":3}
new_dict = add_symbol_to_keys_except_last(original_dict,",")# {'"key1",': 1, '"key2",': 2, '"key3"': 3}print(new_dict)
数学运算
符号运算
复杂符号表达式转python函数
from sympy import symbols, cse
# 提取重复项作为函数参数defextract_symbols(expr):
symbols_set =set()for atom in expr.atoms():if atom.is_symbol:
symbols_set.add(atom)return symbols_set
# 化简表达式并生成Python函数defgenerate_simplified_func(symbol_expr):
common_subexprs, simplified_expr = cse(symbol_expr)
symbols = extract_symbols(symbol_expr)
sorted_symbols =sorted(list(symbols), key=lambda x: x.name)
function_args =", ".join(str(symbol)for symbol in sorted_symbols)
function_body =""for common_subexpr in common_subexprs:
function_body +=f"\t{common_subexpr[0]} = {common_subexpr[1]}\n"
function_body +=f"\treturn {simplified_expr[0]}"
function_code =f"def func({function_args}):\n{function_body}"return function_code
if __name__ =="__main__":# 定义符号变量
a, b, c = symbols('a b c')# 定义复杂的符号表达式
symbol_expr = a * b + a *(a * b + c)+ b *(a *(a * b + c))# 主函数
function_code = generate_simplified_func(symbol_expr)print(f"化简前:\n{symbol_expr}")print(f"化简后:\n{function_code}")
进程操作
VsCode:通过命令行调用实现对某一文件的格式化
import os
import subprocess
defformat_cpp_file(file_path):ifnot os.path.exists(file_path):print("错误:文件不存在。")returntry:
subprocess.run(['E:/environment/vscode/Microsoft VS Code/code.exe','--install-extension','ms-vscode.cpptools'])
subprocess.run(['E:/environment/vscode/Microsoft VS Code/code.exe','--format',f'"{file_path}"'])print("格式化完成。")except Exception as e:print("格式化失败:", e)if __name__ =="__main__":
file_to_format ="E:/ProjectCpp/test/A01.Algorithm/scripts/python/main.cpp"
format_cpp_file(file_to_format)