第六章 組合數(shù)據(jù)類型
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-755295.html
6.1 隨機(jī)密碼生成
import random
import string
# 生成密碼的長(zhǎng)度
password_length = 8
# 生成密碼的字符集,包括大小寫字母和數(shù)字
charset = string.ascii_letters + string.digits
# 生成10個(gè)密碼
for i in range(10):
password = ''.join(random.choice(charset) for _ in range(password_length))
print(password)
6.2 重復(fù)元素判定
from collections import Counter
def check_duplicate(lst):
# 使用Counter統(tǒng)計(jì)每個(gè)元素出現(xiàn)的次數(shù)
count = Counter(lst)
# 遍歷Counter,如果某個(gè)元素出現(xiàn)次數(shù)大于1,則說(shuō)明該元素在列表中出現(xiàn)了不止一次
for element in count:
if count[element] > 1:
return True
# 如果列表中沒有元素出現(xiàn)不止一次,則返回False
return False
# 測(cè)試函數(shù)
lst1 = [1, 2, 3, 4, 5]
lst2 = [1, 2, 3, 2, 4]
print(check_duplicate(lst1)) # False
print(check_duplicate(lst2)) # True
# 驗(yàn)證原列表未被改變
print(lst1) # [1, 2, 3, 4, 5]
print(lst2) # [1, 2, 3, 2, 4]
6.3 重復(fù)元素判定續(xù)
def check_duplicate(lst):
# 利用集合的無(wú)重復(fù)性,將列表去重后和原列表比較長(zhǎng)度,判斷是否存在重復(fù)元素
return len(lst) != len(set(lst))
# 測(cè)試函數(shù)
lst1 = [1, 2, 3, 4, 5]
lst2 = [1, 2, 3, 2, 4]
print(check_duplicate(lst1)) # False
print(check_duplicate(lst2)) # True
# 驗(yàn)證原列表未被改變
print(lst1) # [1, 2, 3, 4, 5]
print(lst2) # [1, 2, 3, 2, 4]
6.4 文本字符分析
from collections import Counter
# 接收字符串
s = input("請(qǐng)輸入字符串:")
# 使用 Counter 統(tǒng)計(jì)每個(gè)字符出現(xiàn)的次數(shù)
char_count = Counter(s)
# 按字符出現(xiàn)的次數(shù)降序排序
char_count = sorted(char_count.items(), key=lambda x: x[1], reverse=True)
# 打印結(jié)果
for char, count in char_count:
print(f"字符 '{char}' 出現(xiàn)了 {count} 次")
6.5 生日悖論分析
import random
def has_duplicates(lst):
"""
檢查列表中是否存在重復(fù)元素
"""
return len(lst) != len(set(lst))
def simulate_birthday_paradox(num_trials, num_people):
"""
模擬生日悖論,返回在num_trials次實(shí)驗(yàn)中,至少有兩個(gè)人生日相同的比例
"""
num_successes = 0 # 記錄出現(xiàn)至少一組生日相同的實(shí)驗(yàn)次數(shù)
for i in range(num_trials):
birthdays = [random.randint(1, 365) for j in range(num_people)]
if has_duplicates(birthdays):
num_successes += 1
return num_successes / num_trials
# 模擬不同隨機(jī)樣本數(shù)量下23個(gè)人中至少有兩個(gè)人生日相同的概率
for num_people in [23, 50, 100]:
for num_trials in [1000, 10000, 100000]:
p = simulate_birthday_paradox(num_trials, num_people)
print(f"{num_trials}次實(shí)驗(yàn),{num_people}個(gè)人中至少有兩個(gè)人生日相同的概率為{p:.4f}")
6.6 《紅樓夢(mèng)》人物統(tǒng)計(jì)
import jieba
from collections import Counter
# 讀取《紅樓夢(mèng)》文本
with open("紅樓夢(mèng).txt", encoding="utf8") as f:
text = f.read()
# 使用結(jié)巴分詞對(duì)文本進(jìn)行分詞
words = jieba.cut(text)
# 統(tǒng)計(jì)每個(gè)詞出現(xiàn)的頻率
word_count = Counter(words)
# 讀取人物名單
with open("hlm_person.txt", encoding="utf8") as f:
person_list = f.read().splitlines()
# 篩選人物名字并統(tǒng)計(jì)出現(xiàn)次數(shù)
person_count = Counter({k:v for k,v in word_count.items() if k in person_list})
# 輸出前20位出現(xiàn)最多的人物名和出現(xiàn)次數(shù)
for name, count in person_count.most_common(20):
print(f"{name}: {count}")
注:上述代碼僅供參考,若有問題可在評(píng)論區(qū)留言!
《紅樓夢(mèng)》及人物名單TXT(百度云鏈接失效可在評(píng)論區(qū)留言)
鏈接:https://pan.baidu.com/s/1MSg0f-DruqDU4mbgJ5Tk7w?pwd=9999
提取碼:9999文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-755295.html
到了這里,關(guān)于《python語(yǔ)言程序設(shè)計(jì)基礎(chǔ)》(第二版)第六章課后習(xí)題參考答案的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!