from itertools import product n = 18 start = (1, 17, 31, 41) table = list(start) while len(table) <= n: next = max(table) + 1 while True: next_is_ok = True for i in table: for couple in product(table, repeat=2): if couple[0] + couple[1] == i + next: next_is_ok = False if next_is_ok: table.append(next) print(table) break next += 1 print(table[-1], ",", sum(table))