第六章课后习题 6.1-6.5

 

 

 

6.1 随机密码生成
 import random
import string 

char = string.ascii_uppercase + string.ascii_lowercase + "123456789"
words = []
for i in range(10):
    for i in range(8):
        password = "".join(random.choice(char))
        words.append(password) 
    print(words)
    words.clear()

 

6.2 重复元素判定
def chongfu(s):
    ls = list(s)
    count = 0
    for i in range(len(ls)):
        for k in range(len(ls)):
            if ls[i] == ls[k]:
                count += 1
    if count >= 1:
        return True
    else:
        return False

s = input()
print(chongfu(s))

 

6.4 文本字符分析
 from collections import Counter

def frequency(s):
    char_count = Counter(s)
    sorted_char_count = sorted(char_count.items(), key = lambda x: x[1], reversed=True)
    for char, count in sorted_char_count:
        print(f"{char}:{count}")

if name == "_main_":
    text = input()
    frequency(text)

 

6.5
 import random
import matplotlib,pyplot as plt 

def same_birthdays(num_people):
    birthdays = [random.randint(1,365) for _ in range(num_people)]
    return len(birthdays) != len(set(birthdays))

def simulate_birthday_problem(num_people, num_samples):
    duplicates = 0
    for _ in range(num_samples):
        if has_duplicate_birthdays(num_people):
            duplicates += 1
    return duplicates / num_samples

def run_simulations():
    num_people = 23
    samples_sizes = [100, 500, 1000, 5000, 10000, 20000, 50000, 100000]
    probailities = []
    for size in samples_sizes:
        prob = simulate_birthday_problem(num_people, size)
        probailities.append(prob)
        print(f"样本量:{size:6d} - 概率:{prob:.4f}({prob*100:.2f}%)")
    
    plt.figure(figsize = (10, 6))
    plt.plot(samples_sizes, probailities, 'bo-', label = '模拟概率')
    plt.axhline(y=0.5073, color='r', linestyle='--', label='模拟概率(50.73%)')
    plt.xscale('log')
    plt.xlabel('样本量(对数尺度)')
    plt.ylabel('至少两人生日相同的概率')
    plt.title('23人中至少两人生日相同的概率 vs 样本量')
    plt.legend()
    plt.grid(True, which="both", ls="--")
    plt.show()

if _name_ == "__main__":
    run_simulations()

 

posted @ 2025-04-24 23:26  与尔5  阅读(6)  评论(0)    收藏  举报