Using a recursive approach -
Using a recursive approach -
Test code:
Test code:
Output:
Output:
7 + 11 + 2 = 20
14 + 4 + 1 + 1 = 20
5 + 10 + 3 + 2 = 20
1 + 17 + 1 + 1 = 20
1 + 5 + 13 + 1 = 20
3 + 12 + 2 + 3 = 20
17 + 2 + 1 = 20
18 + 2 = 20
3 + 12 + 3 + 2 = 20
18 + 1 + 1 = 20
Using iterative approach -
from random import randint
def sequence(n):
a, m, c = [], randint(1, n), n
while n > m > 0:
a.append(str(m))
n -= m
m = randint(0, n)
if n: a += [str(n)]
return ' + '.join(a) + ' = %d' % c
Test code:
for i in xrange(10):
print sequence(20)
Ouput:
19 + 1 = 20
2 + 15 + 3 = 20
2 + 3 + 12 + 3 = 20
19 + 1 = 20
2 + 10 + 2 + 6 = 20
6 + 3 + 9 + 1 + 1 = 20
14 + 2 + 3 + 1 = 20
3 + 7 + 4 + 4 + 2 = 20
9 + 7 + 3 + 1 = 20
3 + 17 = 20