fork download
  1. from collections import defaultdict
  2. import random
  3.  
  4. def sumdisttest(arr):
  5. n = len(arr)
  6. res = 0
  7. for i in range(n):
  8. ctr = set()
  9. for j in range(i, n):
  10. ctr.add(arr[j])
  11. res += len(ctr)
  12. return res
  13.  
  14. def sumdist(arr):
  15. n = len(arr)
  16. last = defaultdict(lambda: -1)
  17. res = 0
  18. for i in range(n):
  19. res += (i - last[arr[i]]) * (n - i)
  20. last[arr[i]] = i
  21. return res
  22.  
  23. for _ in range(10):
  24. arr = random.choices(range(1, 51), k = 1000)
  25. print("PASS" if sumdist(arr) == sumdisttest(arr) else "FAIL")
Success #stdin #stdout 1.15s 10052KB
stdin
1 2 1 3
stdout
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS