import random
# 示例数据
user_items = {
'User1': ['Item1', 'Item2', 'Item3'],
'User2': ['Item2', 'Item4'],
'User3': ['Item1', 'Item3', 'Item5'],
'User4': ['Item2', 'Item3', 'Item4']
}
item_users = {}
for user, items in user_items.items():
for item in items:
if item not in item_users:
item_users[item] = []
item_users[item].append(user)
def recommend(user):
recommended_items = set()
user_items_list = user_items.get(user, [])
# 根据用户已有的物品推荐其他用户喜欢的物品
for item in user_items_list:
if item in item_users:
recommended_items.update(item_users[item])
# 去除用户已有的物品和重复推荐的物品
recommended_items -= set(user_items_list)
# 随机选择一些推荐物品
recommended_items = random.sample(recommended_items, min(5, len(recommended_items)))
return recommended_items
# 调用推荐函数并打印结果
user = 'User1'
recommendations = recommend(user)
print(f"为用户 '{user}' 推荐的物品: {recommendations}")