code ko nhanh nhưng mà đẹp
from itertools import permutations
def concat(p, pattern):
'''
concat((0, 1, 2), 'ABCB') -> -1
concat((1, 0, 2), 'ABCB') -> 1020
'''
n = p[ord(pattern[0].lower()) - ord('a')]
if n == 0: return 0 if len(pattern) == 1 else -1
for ch in pattern[1:]:
n = 10*n + p[ord(ch.lower()) - ord('a')]
return n
def satisfy(p, x, y, z, op):
'''
Check if X op Y == Z
where X = concat(p, x),
Y = concat(p, y),
Z = concat(p, z),
and op in '+-*/'
'''
X, Y, Z = concat(p, x), concat(p, y), concat(p, z)
if X < 0 or Y < 0 or Z < 0: return False
if op == '+': return X + Y == Z
if op == '-': return X - Y == Z
if op == '*': return X * Y == Z
if op == '/': return X / Y == Z and X % Y == 0
return False
def satisfy_condition(p, cond):
'''
Check if `p` satisfies condition `cond`
'''
x, op, y, eq, z = cond.split()
return satisfy(p, x, y, z, op)
def satisfy_conditions(p, conditions):
'''
Check if `p` satisfies all `conditions`
'''
return all(satisfy_condition(p, cond) for cond in conditions)
if __name__ == '__main__':
conditions = (
'ABCB - DEFC = GAFB',
'DH * AB = IEI',
'GGE + DEBB = DHDG',
'ABCB / DH = GGE',
'DEFC + AB = DEBB',
'GAFB - IEI = DHDG'
)
for p in permutations(range(9)):
if satisfy_conditions(p, conditions):
print(p)