from itertools import combinations
from lib_prime import primes


def get_replacements(n):
    n = str(n)
    xss = [[i for i in range(0, len(n)) if n[i] == d]
           for d in "0123456789"]
    xss = [x
           for xs in xss if xs
           for i in range(1, len(xs) + 1)
           for x in combinations(xs, i)]
    xss = ["".join(['x' if i in xs else d for i, d in enumerate(n)])
           for xs in xss]
    return xss


def euler_051():
    replacements = {}
    ps = primes(1000000)
    for p in ps:
        for r in get_replacements(p):
            try:
                replacements[r].append(p)
                if len(replacements[r]) == 8:
                    # print(replacements[r])
                    s = replacements[r][0]
                    return s
            except KeyError:
                replacements[r] = [p]
        if p > 1000000:
            break
    return s


if __name__ == "__main__":
    print("e051.py: " + str(euler_051()))
    assert(euler_051() == 121313)
