The Ulam Sequence is a recursive sequence that begins with two numbers; for example [1, 2]. The next number in the sequence is the smallest unique sum of any 2 numbers in the sequence.
Example:
[u0, u1] = [1, 2]
u2 = 1 + 2 = 3 --> [1, 2, 3]
u3 = 1 + 3 = 4 --> [1, 2, 3, 4]
u4 = 4 + 2 = 6 --> [1, 2, 3, 4, 6]
Notice that 5 is left out. Though 5 is smaller than 6, 5 can be written as a sum in 2 different ways: 4 + 1 and 3 + 2; therefore, it is not unique; whereas, 6 is unique since it is only the sum of 4 + 2.
Write a code that generates an Ulam Sequence of length n and starts with u0, u1.
Ex:
f(u0=1, u1=2, n=10) = [1, 2, 3, 4, 6, 8, 11, 13, 16, 18]
def ulam_sequence(u0, u1, n):
u = [u0, u1]
nn = u[-1] + 1
while len(u) < n:
count = 0
for i in u:
if nn - i in u and nn - i != i:
count += 1
if count >= 3:
break
nn += 1
if count == 2:
u.append(nn)
nn += 1
return u
test.assert_equals(ulam_sequence(3, 4, 5), [3, 4, 7, 10, 11])
test.assert_equals(ulam_sequence(1, 2, 10), [1, 2, 3, 4, 6, 8, 11, 13, 16, 18])
test.assert_equals(ulam_sequence(2, 3, 8), [2, 3, 5, 7, 8, 9, 13, 14])