Project Euler 68

こちらから問題の日本語訳を見ることができます。
Problem 68 - PukiWiki

最初に、合計が同じになる三つの数の組み合わせをすべて見つけます。(init_values)
このうちの5つを組み合わせて 5-gon ring を構成しす。(depth_first)

これを、つなげてできる数字のうちもっとも大きなものが解となります。
以下,Python によるコードです。

from Euler import flatten
def init_values(goal, length, limit):
    if len(stack) > length -1:
        if sum(stack) == goal:
            candidates.append([x for x in stack])
        return
    for i in range(1, limit+1):
        if sum(stack) + i > goal or i in stack:
            continue
        stack.append(i)
        init_values(goal, length, limit)
        stack.pop()
    
def depth_first(length):
    if len(stack) == length:
        tmp = flatten(stack)
        if stack[-1][2:] == stack[0][1:-1] and len(set(tmp)) == 10 and sum(len(str(x)) for x in tmp) == 16:
            ans.append(tmp)
        return
    for c in candidates:
        if stack != [] and stack[-1][2:] != c[1:-1]:
            continue
        if stack != [] and stack[0][0] > c[0]:
            continue
        if len(stack) < 4 and len(set(flatten(stack)+c)) != len(stack)*2 + 3:
            continue
        stack.append(c)
        depth_first(length)
        stack.pop()

max_num = 0
for i in range(3, 31):
    candidates, stack, ans = [], [], []
    init_values(i, 3, 10)
    depth_first(5)
    tmp = [int(reduce(lambda x,y: x+str(y), ls, '')) for ls in ans]
    if tmp != []:
        tmp = max(tmp)
        if max_num < tmp :
            max_num = tmp
    print i

print max_num