From 70235c909038c15b1155ad87bb7254f170fbf33f Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sat, 3 Jul 2021 21:28:47 -0400 Subject: [PATCH] Change problem 121 to look cooler but make it harder to understand --- python/e121.py | 30 +++++++----------------------- 1 file changed, 7 insertions(+), 23 deletions(-) diff --git a/python/e121.py b/python/e121.py index 5b9fbab..5910764 100644 --- a/python/e121.py +++ b/python/e121.py @@ -1,41 +1,25 @@ -from fractions import Fraction +from math import factorial from itertools import combinations -def mul(xs): +def product(xs): r = 1 for x in xs: r *= x return r -def mul_inv(xs): - r = 1 - for x in xs: - r *= (1 - x) - return r - - def sub_odds(n_blue, n_total): - """ Computes the odds for getting exactly n_blue out of n_total blue discs. - """ - total_odds = 0 - odds = [Fraction(1, n) for n in range(2, 2 + n_total)] - odds_set = set(odds) - for odd in combinations(odds, n_blue): - odd_inv = tuple(odds_set.difference(set(odd))) - total_odds += mul(odd) * mul_inv(odd_inv) - return total_odds + odds = [n for n in range(1, n_total + 1)] + return sum(map(product, combinations(odds, n_total - n_blue))) def euler_121(): n_turns = 15 n_to_win = n_turns // 2 + 1 - odds = 0 - for n_blue in range(n_to_win, n_turns + 1): - odds += sub_odds(n_blue, n_turns) - price = int(1 / odds) - return price + odds = sum([sub_odds(n_blue, n_turns) + for n_blue in range(n_to_win, n_turns + 1)]) + return int(factorial(n_turns + 1) / odds) if __name__ == "__main__":