Created
October 29, 2021 13:53
-
-
Save 1f0/883cc03b7aa8f418130b5b3ea8b04c72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def partition(n): | |
# x: current coin, y: remain value | |
def helper(x, y): | |
if y <= 0: | |
return int(y == 0) | |
# use x and not use x | |
z = helper(x, y-x) | |
if x < y: | |
z += helper(x+1, y) | |
return z | |
return helper(1, n) | |
if __name__ == '__main__': | |
ans = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, \ | |
56, 77, 101, 135, 176, 231, 297, 385, 490] | |
for i, p in enumerate(ans): | |
assert partition(i) == p | |
Restrict to odd
def only_one_odd(lst):
return sum([i%2 for i in lst]) == 1
def help(n)->list:
ans = set()
ans.add((n,))
for x in range(1, n):
for y in help(n - x):
z = (x,) + y
if only_one_odd(z):
ans.add(tuple(sorted(z)))
return ans
def solution(n):
ans = help(n)
for x in sorted(ans):
print(n, '=', '+'.join([str(i) for i in x]), sep='')
solution(1)
solution(5)
solution(9)
Result:
1=1
5=1+2+2
5=1+4
5=2+3
5=5
9=1+2+2+2+2
9=1+2+2+4
9=1+2+6
9=1+4+4
9=1+8
9=2+2+2+3
9=2+2+5
9=2+3+4
9=2+7
9=3+6
9=4+5
9=9
Only prime
def is_prime(p):
if p < 2:
return False
for x in range(2, int(p**0.5)+1):
if p%x == 0:
return False
return True
def only_prime(lst):
return sum([is_prime(i) for i in lst]) == len(lst)
def only_one_odd(lst):
return sum([i%2 for i in lst]) == 1
def help(n)->list:
ans = set()
z = (n,)
if only_prime(z):
ans.add(z)
for x in range(1, n):
for y in help(n - x):
z = (x,) + y
if only_prime(z):
ans.add(tuple(sorted(z)))
return ans
def solution(n):
ans = help(n)
for x in sorted(ans):
print(n, '=', '+'.join([str(i) for i in x]), sep='')
solution(3)
solution(5)
solution(9)
Result:
3=3
5=2+3
5=5
9=2+2+2+3
9=2+2+5
9=2+7
9=3+3+3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Print all