Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
(Shorter code) Recursively generate parenthesization on split digits and operations solution in Clear category for Mathematically Lucky Tickets by Phil15
from itertools import product, combinations
from operator import add, sub, mul
from math import inf # Manage the division by zero.
div = lambda a, b: a / b if b!=0 else inf
def parenthesizations(seq, op):
"""
Generate all possibles parenthesizations in SEQuence with OPerations
Work with all possibles types, if operations allow it.
>>> list(parenthesizations(['1','2','3'], [add, mul])) # 1+2*3 with ()
['1 + (2 * 3)', '(1 + 2) * 3']
"""
if len(seq)==1:
yield seq[0]
else:
for i in range(1, len(seq)):
seq_left, seq_right = seq[:i], seq[i:]
op_left, op_middle, op_right = op[:i-1], op[i-1], op[i:]
for left in parenthesizations(seq_left, op_left):
for right in parenthesizations(seq_right, op_right):
yield op_middle(left, right)
def split(digits, indexes):
"""
Split digits string with indexes.
>>> split('012345', [2, 5])
[1, 234, 5]
"""
return [int(digits[start:end])
for (start, end) in zip([0]+indexes, indexes+[6])]
def checkio(digits):
"""Say if the 6-digits "digits" is lucky.
It's lucky if it can't be split and evaluated (with + - * /) to 100."""
return all(100 not in parenthesizations(split(digits, list(indexes)), signs)
for k in range(6, 0, -1)
for indexes in combinations(range(1, 6), k-1)
for signs in product((add, sub, mul, div), repeat=k-1))
Aug. 18, 2018
Comments: