def solution(l): nodes = {i: [] for i in range(len(l))} for i in range(len(l)): for j in range(i+1, len(l)): x, y = l[i], l[j] if y % x == 0: nodes[i] += [j] result = 0 for i in nodes: for j in nodes[i]: result += len(nodes[j]) return result tests = [ ([1, 1, 1], 1), ([1, 2, 3, 4, 5, 6], 3), ([2, 3, 4], 0), ([1, 1, 2, 3, 4, 5, 6], 11), ] for i, o in tests: result = solution(i) print(i, result == o, result, o)