round(H, 3) 保留到 3 位小数。json.dumps 输出,保证双引号格式。import sys
import json
import math
def compute_entropy(counts):
# counts: dict[str, int],各类别阅读次数
total = sum(counts.values())
if total == 0:
return 0.0
H = 0.0
for c in counts.values():
if c <= 0:
continue
p = c / total
H -= p * math.log2(p)
return H
def main():
# 从标准输入读取整段字符串(单行或多行都可)
raw = sys.stdin.read().strip()
decoder = json.JSONDecoder()
data, end = decoder.raw_decode(raw) # 只取开头的第一个 JSON;忽略后面的内容
result = {}
for user, cat_counts in data.items():
H = compute_entropy(cat_counts)
result[user] = {"entropy": round(H, 3)}
# 输出为合法 JSON,双引号格式
print(json.dumps(result, ensure_ascii=False))
if __name__ == "__main__":
main()
你正在为一个新闻推荐系统工作,该系统根据用户的阅读历史和新闻的类别来推荐新闻。
给定一个用户的阅读历史数据,每个用户有多个新闻类别的阅读次数。
我们希望计算每个用户阅读新闻类别的信息熵。
信息熵的计算公式为:H=−∑i=1npilog2Pi
其中,pi 是用户阅读第 i 类新闻的概率,n 是新闻类别的数量。
你需要编写一个 Python 函数,该函数接受上述格式的输入数据,从终端读取输入,然后计算每个用户的信息熵,并将结果保留到 3 位小数并输出到终端。
输入是一个字典,键是用户的 id (字符串),值是一个字典,包含多个键,分别代表用户的历史阅读的新闻类型。
返回一个字典,格式与输入相同,但是输出每个用户的信息。注意输出的引号格式。
输入
{"user1":{"sports":10, "technology":20,"entertainment":30},"user2":{"sports":20,"technology":30,"entertainment":10},"user3":{"sports":30,"technology":10,"entertainment":20}}
输出
{"user1":{"entropy":1.459},"user2":{"entropy":1.459},"user3":{"entropy"1.459}}