import math
import time
import numpy as np


topicIds = [[1, 2, 3], [2, 3, 4], [1, 4], [2, 3]]
answerIds = [[6, 4], [1, 2], [5], [3]]
views = [[2, 1, 2], [6, 3, 5], [3, 3, 0], [5, 1, 1], [4, 2, 3], [1, 4, 2]]

flatten = lambda l: [item for sublist in l for item in sublist]
unique = lambda l: list(set(l))
limit = lambda l: l[0:max(10, len(l))]
topic_ids_all = unique(flatten(topicIds))
user_ids_all = unique([item[1] for item in views])
print(topic_ids_all)
print(user_ids_all)


topic_to_answers = {}
topic_user_to_views = {}
result = []
for topic in sorted(topic_ids_all):
    topic_to_answers[topic] = flatten([answerIds[i] for i, elem in enumerate(topicIds) if topic in elem])
    views_to_answer = [elem[1:] for elem in views for answer in topic_to_answers[topic] if elem[0] == answer]
    for user_views in views_to_answer:
        key = (topic, user_views[0])
        if not key in topic_user_to_views:
            topic_user_to_views[key] = [user_views[1]]
        else:
            topic_user_to_views[key].append(user_views[1])

print(topic_to_answers)
print(topic_user_to_views)
topic_user_to_views = {k: sum(v) for k, v in topic_user_to_views.items()}
print(topic_user_to_views)

for topic in sorted(topic_ids_all):
    result.append([[k[1], v] for k, v in topic_user_to_views.items() if k[0] == topic])

# result.sort(key=lambda ll: (lambda l: l[1])(ll))
result = [limit(sorted(item, key = lambda x: (x[1], -x[0]), reverse=True)) for item in result]
# print(type(result[0].sort()))
[print(x) for x in result]



