Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import time
  2. from collections import Counter
  3. from pprint import pprint
  4.  
  5.  
  6. def all_sums(values, threshold, previous_sums=None):
  7. """
  8. values must be sorted
  9. previous_sums is a Counter of previously obtained possible sums
  10.  
  11. Returns a Counter of all possible sums of values and the previous sums
  12. """
  13. if not previous_sums:
  14. previous_sums = Counter({0: 1})
  15.  
  16. new = Counter()
  17. for existing_sum, ex_sum_count in sorted(previous_sums.items()):
  18. for index, val in enumerate(values):
  19. total = existing_sum + val
  20. if total < threshold:
  21. # With the current value, we have found ex_sum_count
  22. # ways to obtain that total
  23. new.update({total: ex_sum_count})
  24. else:
  25. # We don't need the exact sum, as anything we could
  26. # later add to it will be over the threshold.
  27. # We count them under the value = threshold
  28. # As 'values' is sorted, all subsequent values will also give
  29. # a sum over the threshold
  30. values_left = len(values) - index
  31. new.update({threshold: values_left * ex_sum_count})
  32. break
  33. return new
  34.  
  35.  
  36. def count_sums(values, threshold, repeat):
  37. """
  38. values must be sorted!
  39.  
  40. Recursively calculates the possible sums of 'repeat' values,
  41. counting together all values over 'threshold'
  42. """
  43. if repeat == 1:
  44. return all_sums(values, threshold, previous_sums=None)
  45. else:
  46. return all_sums(values, threshold, previous_sums=count_sums(values, threshold, repeat=repeat - 1))
  47.  
  48.  
  49. if __name__ == '__main__':
  50. start_time = time.time()
  51. confs = range(10, 11)
  52.  
  53. for i in confs:
  54. loops = i
  55. results = [4, 2.75, 2.75, 2.75, 2.75, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 0.25, 0.25, 0.25, 0.25, 0]
  56. threshold = loops * 2
  57. values = sorted(results)
  58. sums = count_sums(values, threshold, repeat=loops)
  59. number_of_sums = len(results) ** loops
  60. good = sums[threshold]
  61. bad = number_of_sums - good
  62. print("Questions: {0}, Result: {1:.6f}%, time elapsed: {2:.2f}s".format(i, 100 * good / (good + bad),
  63. time.time() - start_time))
  64. pprint(sums)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement