以下是 3 个应用“Python 集合”知识的综合应用项目,这些项目具有新颖性、前瞻性和实用性,每个项目都包含完整的代码、解释说明、测试案例和执行结果。
在生物信息学中,比对两个基因序列的相似性。使用集合的交集和并集计算相似度。
# 基因序列(简化为字符串集合)
sequence1 = {"A", "T", "C", "A", "A", "A"}
sequence2 = {"A", "C", "G", "G", "T", "T"}
# 计算相似度
def sequence_similarity(seq1, seq2):
intersection = seq1 & seq2 # 交集
union = seq1 | seq2 # 并集
similarity = len(intersection) / len(union)
return similarity
# 测试
similarity = sequence_similarity(sequence1, sequence2)
print(f"基因序列相似度:{similarity:.2f}")
{"A", "T", "C", "A", "A", "A"}
{"A", "C", "G", "G", "T", "T"}
基因序列相似度:0.75
设计一个简单的推荐系统,基于用户的历史行为和兴趣标签,推荐新的内容。使用集合的交集运算找到用户可能感兴趣的内容。
# 用户兴趣标签和历史行为
user_interests = {"python", "AI", "machine learning", "data science"}
content_tags = {
"article1": {"python", "data science"},
"article2": {"AI", "deep learning"},
"article3": {"machine learning", "statistics"},
"article4": {"python", "web development"},
}
# 推荐函数
def recommend_content(user_interests, content_tags):
recommendations = {}
for content, tags in content_tags.items():
common_tags = user_interests & tags # 计算交集
if common_tags:
recommendations[content] = common_tags
return recommendations
# 测试
recommendations = recommend_content(user_interests, content_tags)
print("推荐内容及共同兴趣标签:")
for content, tags in recommendations.items():
print(f"{content}: {tags}")
{"python", "AI", "machine learning", "data science"}
article1
: {"python", "data science"}
article2
: {"AI", "deep learning"}
article3
: {"machine learning", "statistics"}
article4
: {"python", "web development"}
推荐内容及共同兴趣标签:
article1: {'python', 'data science'}
article2: {'AI'}
article3: {'machine learning'}
article4: {'python'}
分析服务器日志,统计独立 IP 地址的数量,并找出访问量最高的 IP 地址。
# 模拟日志数据
logs = [
"192.168.1.1 - GET /index.html",
"192.168.1.2 - GET /about.html",
"192.168.1.1 - POST /login",
"192.168.1.3 - GET /index.html",
"192.168.1.2 - GET /contact.html",
]
# 统计独立 IP 地址
unique_ips = set(log.split()[0] for log in logs)
print(f"独立 IP 地址数量:{len(unique_ips)}")
# 统计访问量最高的 IP 地址
from collections import Counter
ip_counter = Counter(log.split()[0] for log in logs)
most_common_ip = ip_counter.most_common(1)[0]
print(f"访问量最高的 IP 地址:{most_common_ip[0]},访问次数:{most_common_ip[1]}")
192.168.1.1 - GET /index.html
192.168.1.2 - GET /about.html
192.168.1.1 - POST /login
192.168.1.3 - GET /index.html
192.168.1.2 - GET /contact.html
独立 IP 地址数量:3
访问量最高的 IP 地址:192.168.1.1,访问次数:2
这些项目展示了 Python 集合在实际问题中的广泛应用,包括基因分析对比、文章推荐系统、运行日志分析等方面。通过这些项目,可以深入理解集合的强大功能和灵活性。