-
-
Save vovanz/05e6c578a6a94c66730d53abe6a4934e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fractions import Fraction | |
SUM = 0 | |
SUBTRACT = 1 | |
MULTIPLY = 2 | |
DIVIDE = 3 | |
OPERATIONS_LIST = [ | |
SUM, SUBTRACT, MULTIPLY, DIVIDE | |
] | |
OPERATIONS = { | |
SUM: lambda a, b: a + b, | |
SUBTRACT: lambda a, b: a - b, | |
MULTIPLY: lambda a, b: a * b, | |
DIVIDE: lambda a, b: a / b | |
} | |
OPERATIONS_STR = { | |
SUM: '+', | |
SUBTRACT: '-', | |
MULTIPLY: '*', | |
DIVIDE: '/', | |
} | |
def is_6_digit_number(s: str): | |
if len(s) != 6: | |
return False | |
try: | |
int(s) | |
return True | |
except: | |
return False | |
def iter_splittings(s: str): | |
if not s: | |
yield [] | |
for i in range(1, len(s) + 1): | |
for splitting in iter_splittings(s[i:]): | |
yield [s[0:i]] + splitting | |
def iter_operations_orders(l: list): | |
yield l | |
for i in range(2, len(l)): | |
for operations_order in iter_operations_orders(l[i:]): | |
yield [l[0:i]] + operations_order | |
yield l[0:i] + operations_order | |
for i in range(1, len(l) - 1): | |
for operations_order in iter_operations_orders(l[i:]): | |
yield l[0:i] + [operations_order] | |
yield l[0:i] + operations_order | |
def iter_operations(num: int): | |
if num > 0: | |
for op in OPERATIONS_LIST: | |
for ops in iter_operations(num - 1): | |
yield [op] + ops | |
else: | |
yield [] | |
def apply_operation(a, b, op): | |
return OPERATIONS[op](a, b) | |
def apply_operations(nums, ops): | |
num = nums[0] | |
if len(nums) == 1: | |
if isinstance(num, Fraction): | |
yield nums[0], str(nums[0].numerator) | |
else: | |
yield from apply_operations(num, ops) | |
else: | |
if isinstance(num, Fraction): | |
op = ops[0] | |
for r, s in apply_operations(nums[1:], ops[1:]): | |
try: | |
yield apply_operation(num, r, op), '({} {} {})'.format( | |
str(nums[0].numerator), OPERATIONS_STR[op], s | |
) | |
except ZeroDivisionError: | |
pass | |
else: | |
op = ops[len(num) - 1] | |
for r1, s1 in apply_operations(num, ops[:len(num) - 1]): | |
for r2, s2 in apply_operations(nums[1:], ops[len(num):]): | |
try: | |
yield apply_operation(r1, r2, op), '({} {} {})'.format( | |
s1, OPERATIONS_STR[op], s2 | |
) | |
except ZeroDivisionError: | |
pass | |
def get100(s: str): | |
for splitting in iter_splittings(s): | |
splitting = [ | |
Fraction(s) for s in splitting | |
] | |
for operations_order in iter_operations_orders(splitting): | |
for ops in iter_operations(len(splitting) - 1): | |
for r, s in apply_operations(operations_order, ops): | |
if r == Fraction(100): | |
yield '{} = {}'.format(s, r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment