Project Euler Problem 33 Solution

Project Euler Problem 33 Solution

Digit Cancelling Fractions

by {BetaProjects} | Project Euler & HackerRank

Project Euler Problem 33 Statement

Solution

HackerRank version

HackerRank Project Euler 33: Sum all the Numerators and the Denominators of the original fractions, and print them separated by a space.

Python Source Code

from itertools import combinations, combinations_with_replacement, product

exp = lambda st,n: [f"{s[:i]}{n}{s[i:]}" for s in st for i in range(len(s) + 1)]
combo = lambda n, st: set(st) if not n else combo(n[:-1], exp(st, n[-1]))
def f():
    n, k = map(int, input().split())
    cancel_digits = list(combinations_with_replacement(range(1, 10), r=k))
    base_nums = [p for p in product(range(10), repeat=n-k) if p != (0,) * (n-k)]
    
    valid_fractions = set()
    for cancel_set in cancel_digits:
        pairs = []
        for base in base_nums:
            base_str = ''.join(map(str, base))
            pairs.extend((int(''.join(map(str, base))), int(num)) for num in combo(list(cancel_set), [base_str]) if num[0] != '0')
            
        for (num1, den1), (num2, den2) in combinations(pairs, 2):
            if num1 < num2 and num1 * den2 == num2 * den1:
                valid_fractions.add((den1, den2))
    
    print(sum(x[0] for x in valid_fractions), sum(x[1] for x in valid_fractions))
f()