-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcriptarithmetic.py
More file actions
78 lines (39 loc) · 1.53 KB
/
Copy pathcriptarithmetic.py
File metadata and controls
78 lines (39 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 15:31:57 2019
@author: irina
"""
from __future__ import division
import string, re, itertools
def solve(formula):
"""Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
Input formula is a string; output is a digit-filled-in string or None."""
for f in fill_in(formula):
if valid(f):
return f
def fill_in(formula):
"Generate all possible fillings-in of letters in formula with digits."
letters = "".join(set(re.findall('[A-Z]', formula)))
for digits in itertools.permutations('1234567890', len(letters)):
table = string.maketrans(letters, ''.join(digits))
yield formula.translate(table)
def valid(f):
"""Formula f is valid if and only if it has no
numbers with leading zero, and evals true."""
try:
return not re.search(r'\b0[0-9]', f) and eval(f) is True
except ArithmeticError:
return False
def faster_solve(formula):
"""
Give
def compile_word(word):
"""Compile a word of uppercase letters as numeric digits.
E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'
Non-uppercase words unchanged: compile_word('+') => '+'"""
if word.isupper():
terms = [('%s*%s' % (10**i, d)) for (i,d) in enumerate(word[::-1])]
return '(' + '+'.join(terms) +')'
else:
return word