// Using two stacks to implement queuetypeQueuestruct{inStackStackoutStackStack}func(q *Queue)Enqueue(iteminterface{}){forval,err:=q.outStack.Pop();err==nil{q.inStack.Push(val)}q.inStack.Push(val)}func(q *Queue)Dequeue()(interface{},error){forval,err:=q.inStack.Pop();err==nil{q.outStack.Push(val)}returnq.outStack.Pop()}// Using two queues to implement stacktypeStackstruct{mainQueueQueuebackupQueueQueue}func(s *Stack)Push(iteminterface{}){s.mainQueue.Enqueue(item)}func(s *Stack)Pop()(interface{},error){varvalinterface{}err:=errors.News("empty stack")forv,err:=s.mainQueue.Dequeue();err==nil{val=vs.backupQueue.Enqueue(v)}// switch queuess.backupQueue,s.mainQueue=s.mainQueue,s.backupQueuereturnval,err}
public static class MathExtensions
{
// 尾递归阶乘
public static long Factorial(int n) => FactorialTail(n, 1);
private static long FactorialTail(int n, long acc) =>
n <= 1 ? acc : FactorialTail(n - 1, n * acc);
// 尾递归斐波那契
public static long Fibonacci(int n) => FibonacciTail(n, 0, 1);
private static long FibonacciTail(int n, long a, long b) =>
n == 0 ? a : FibonacciTail(n - 1, b, a + b);
}
// 使用循环的版本(最安全)
public static long FactorialIterative(int n)
{
long result = 1;
for (int i = 2; i <= n; i++)
{
result *= i;
}
return result;
}
def evaluate_rpn(expression):
"""
计算逆波兰表达式(RPN)的值。
:param expression: 逆波兰表达式字符串
:return: 表达式的计算结果
"""
stack = []
for token in expression.split():
if token in '+-*/':
# 弹出栈顶的两个元素作为操作数
b, a = stack.pop(), stack.pop()
if token == '+':
stack.append(a + b)
elif token == '-':
stack.append(a - b)
elif token == '*':
stack.append(a * b)
elif token == '/':
stack.append(a / b) # 注意:这里的除法是浮点数除法
else:
# 将数字推入栈中
stack.append(float(token))
return stack.pop()
def repl():
print("简单的逆波兰表达式(REPL)计算器。输入 'quit' 以退出。")
while True:
expression = input("请输入逆波兰表达式: ")
if expression == "quit":
print("退出REPL。")
break
try:
result = evaluate_rpn(expression)
print("结果:", result)
except Exception as e:
print("错误:", e)
# 启动REPL
repl()
import numpy as np
import random
def generate_maze(size=10):
maze = np.zeros((size, size), dtype=int)
# 初始化墙壁和路径
for x in range(0, size):
for y in range(0, size):
if x % 2 == 0 or y % 2 == 0:
maze[x][y] = 1 # 墙壁
else:
maze[x][y] = 0 # 路径
# 使用Prim算法生成迷宫
def check_neighbors(r, c):
"""检查邻居节点,并返回邻居墙壁的列表"""
walls = []
if r > 1: walls.append((r - 2, c))
if r < size - 2: walls.append((r + 2, c))
if c > 1: walls.append((r, c - 2))
if c < size - 2: walls.append((r, c + 2))
return walls
def break_wall(cell, adj):
"""打破两个单元格之间的墙壁"""
if cell[0] == adj[0]: # 同行
maze[max(cell[0], adj[0])][int((cell[1] + adj[1]) / 2)] = 0
else: # 同列
maze[int((cell[0] + adj[0]) / 2)][max(cell[1], adj[1])] = 0
start_cell = (random.randint(1, (size // 2)) * 2 - 1, random.randint(1, (size // 2)) * 2 - 1)
maze[start_cell[0]][start_cell[1]] = 0
walls = check_neighbors(start_cell[0], start_cell[1])
visited = [start_cell]
while walls:
wall = random.choice(walls)
walls.remove(wall)
adj_cells = check_neighbors(wall[0], wall[1])
adj_visited = [cell for cell in adj_cells if cell in visited]
if len(adj_visited) == 1:
visited_cell = adj_visited[0]
break_wall(visited_cell, wall)
visited.append(wall)
walls.extend([w for w in check_neighbors(wall[0], wall[1]) if w not in visited and w not in walls])
return maze
maze = generate_maze(15)
print(maze)
class MyClass {
public:
int MyNum;
string myString;
}
void CreatePointer()
{
MyClass* p = new MyClass();
// do something
return;
}
public string Read()
{
FileStream fs = new FileStream(@"C:\data.txt", FileMode.Open, FileAccess.Read);
return fs.ReadString();
}
class Container<T> {
private T[] _arr;
public int Count = 0;
public void Push<T>(T elem)
{
_arr[Count] = elem;
Count++;
}
public T Pop<T>()
{
Count--
return _arr[Count];
}
}
public class Random {
public static int round = 10;
public static int Next(int seed) {
for(int i = 0; i < round; i++) {
seed = NextRandom(seed)
}
return seed;
}
private static int NextRandom(int seed){
var result = (seed * seed).ToString();
if (result.Length % 2 == 1) { // if odded
result += "0" + result;
}
var newSeed = result.SubString(1, result.Length - 1);
return Int.Prase(newSeed);
}
}
X = (a * X + c) % m
public class Random {
public static int a;
public static int c;
public static int m;
public static int Next(int X){
return (a * X + c) % m;
}
}
public class Random {
public static int Next(int seed){
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
return (seed < 0)? ~seed + 1; seed;
}
}
class SimpleGarbageCollector:
def __init__(self):
self.managed_objects = {} # 存储对象及其引用计数
def add_object(self, obj_id):
"""添加一个对象,引用计数初始化为1"""
self.managed_objects[obj_id] = 1
def delete_object(self, obj_id):
"""删除一个对象,即减少其引用计数,如果引用计数为0,则释放资源"""
if obj_id in self.managed_objects:
self.managed_objects[obj_id] -= 1
if self.managed_objects[obj_id] == 0:
print(f"对象 {obj_id} 不再被引用,进行垃圾回收。")
del self.managed_objects[obj_id]
def add_reference(self, obj_id):
"""增加对象的引用计数"""
if obj_id in self.managed_objects:
self.managed_objects[obj_id] += 1
def remove_reference(self, obj_id):
"""减少对象的引用计数"""
self.delete_object(obj_id)
# 演示
gc = SimpleGarbageCollector()
gc.add_object("obj1")
gc.add_reference("obj1")
gc.remove_reference("obj1")
gc.remove_reference("obj1") # 这里引用计数为0,触发垃圾回收
class SimpleMessageBroker:
def __init__(self):
self.subscriptions = {} # {message_type: [subscribers]}
def subscribe(self, message_type, subscriber):
"""订阅者订阅特定类型的消息"""
if message_type not in self.subscriptions:
self.subscriptions[message_type] = []
self.subscriptions[message_type].append(subscriber)
def publish(self, message_type, message):
"""发布者发送消息,消息将被转发给订阅了该类型的所有订阅者"""
subscribers = self.subscriptions.get(message_type, [])
for subscriber in subscribers:
subscriber.receive(message)
class Subscriber:
"""订阅者"""
def __init__(self, name):
self.name = name
def receive(self, message):
"""接收来自MessageBroker的消息"""
print(f"{self.name} received message: {message}")
# 示例使用
broker = SimpleMessageBroker()
subscriber1 = Subscriber("Subscriber 1")
subscriber2 = Subscriber("Subscriber 2")
broker.subscribe("news", subscriber1)
broker.subscribe("news", subscriber2)
broker.subscribe("sports", subscriber1)
broker.publish("news", "Breaking News!")
broker.publish("sports", "Sports News Update")
from http.server import BaseHTTPRequestHandler, HTTPServer
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 处理GET请求
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"Welcome to the Simple Python Web Server!")
if __name__ == "__main__":
server_address = ('', 8000) # 监听所有可用的地址和端口8000
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print("Web Server running on port 8000...")
httpd.serve_forever()
import hashlib
import os
def hash_file(filepath):
"""计算文件的SHA-256哈希"""
sha256_hash = hashlib.sha256()
with open(filepath, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def find_duplicates(directory):
"""在给定目录中查找重复文件"""
hashes = {}
duplicates = []
for root, dirs, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_hash = hash_file(filepath)
if file_hash in hashes:
duplicates.append((filepath, hashes[file_hash]))
else:
hashes[file_hash] = filepath
return duplicates
# 示例使用
directory = '/path/to/your/directory'
duplicates = find_duplicates(directory)
for dup in duplicates:
print(f"Duplicate found: {dup[0]} and {dup[1]}")