Advertisement
Guest User

Partitions

a guest
Oct 27th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. from functools import reduce
  2.  
  3. def part(n):
  4.     products = sorted(product(p) for p in partitions(n))
  5.     values = products[-1] - 1, sum(products) / len(products), sorted_median(products)
  6.     return "Range: {} Average: {:.2f} Median {:.2f}".format(*values)
  7.  
  8. def product(arr):
  9.     return reduce(int.__mul__, arr)
  10.  
  11. def is_prime(n):
  12.     d = 2
  13.     while d * d <= n:
  14.         if n % d == 0: return False
  15.         d += 1
  16.     return True
  17.  
  18. def sorted_median(arr):
  19.     return (arr[(len(arr) - 1) // 2] + arr[len(arr) // 2]) / 2
  20.  
  21. def prime_at_least(n):
  22.     while not is_prime(n): n += 1
  23.     return n
  24.  
  25. def partitions(n):
  26.     current = [1] * n
  27.     while current:
  28.         yield current
  29.         current = next_partition(current)
  30.  
  31. def next_partition(partition):
  32.     if len(partition) < 2: return None
  33.  
  34.     suffix_total = sum(partition[-2:])
  35.     new_repeated_value = prime_at_least(partition[-2] + 1)
  36.     repetitions = suffix_total // new_repeated_value - 1
  37.     result = partition[:-2] + [new_repeated_value] * repetitions
  38.     result.append(suffix_total - repetitions * new_repeated_value)
  39.     return result if is_prime(result[-1]) else next_partition(result)
  40.  
  41. n = int(input())
  42. print(part(n))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement