You can download this code by clicking the button below.
This code is now available for download.
Generate a random string of specified length, compress a directory into a zip file, estimate the number of digits of π using the Monte Carlo method, save data to a JSON file, pause the program execution for a specified number of seconds, and print system information.
Technology Stack : random, string, math, shutil, json, time, sys, os
Code Type : Code function
Code Difficulty : Intermediate
import random
import string
import math
import os
import shutil
import json
import time
import sys
def generate_random_string(length=10):
"""生成指定长度的随机字符串
Args:
length (int): 字符串长度,默认为10
Returns:
str: 生成的随机字符串
"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def zip_directory(source_dir, target_zip):
"""将目录压缩成zip文件
Args:
source_dir (str): 需要压缩的目录路径
target_zip (str): 压缩后的zip文件路径
"""
shutil.make_archive(target_zip[:-4], 'zip', source_dir)
def calculate_pi_digits(num_digits):
"""使用蒙特卡洛方法估算π的位数
Args:
num_digits (int): 估算的π的位数
Returns:
float: 估算的π值
"""
inside_circle = 0
total_points = 0
for _ in range(num_digits * 10**6):
x, y = random.random(), random.random()
distance = math.sqrt(x**2 + y**2)
if distance <= 1:
inside_circle += 1
total_points += 1
return (inside_circle / total_points) * 4
def save_data_to_json(data, file_path):
"""将数据保存到JSON文件
Args:
data (dict): 需要保存的数据
file_path (str): JSON文件的路径
"""
with open(file_path, 'w') as f:
json.dump(data, f)
def sleep_for_seconds(seconds):
"""暂停程序执行指定的秒数
Args:
seconds (float): 指定的秒数
"""
time.sleep(seconds)
def print_system_info():
"""打印系统信息"""
print(f"Python version: {sys.version}")
print(f"Platform: {sys.platform}")
print(f"OS name: {os.name}")
print(f"CPU count: {os.cpu_count()}")