Problem:


覆面算

 数式の一部を隠してしまって、隠した数字を探す問題を覆面算といいます。今回は、数式の中のある数字のいくつかを X で隠してしまった式を扱います。以下の数式を入力して、結果を出力するプログラムを作成してください。

  数式

「数字列 + 数字列 = 数字列」の形で、1 行の単純な足し算式です。

 「数字列」は、数字 0 から 9 と文字 X の並びです。

 2 桁以上の「数字列」の左端の数字は 0 ではないものとします。

  X は、数式全体の中で必ず 1 つ以上含まれます。

  結果

  覆面算の答えです。数式が成り立つ様な X の値で 0 ~ 9 のどれか 1 つです。2 つ以上の答えはないものとします。

  答えがない場合、結果は“NA”としてください。

Input

複数のデータセットが与えられます。各データセットとして、X を 1 つ以上含む足し算式(空白を含まない 126 文字以内の文字列) が１行に与えられます。データセットの数は 150 を超えません。

Output

各データセットについて、覆面算の結果を１行に出力してください。数字 0 ~ 9 または NA を出力してください。

Sample Input

123+4X6=X79
12X+4X6=X79
XX22+89=X2XX

Output for the Sample Input

5
NA
1



Sample input:
123+4X6=X79
12X+4X6=X79
XX22+89=X2XX


Sample output:
5
NA
1

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, exit


def main():
    for line in stdin:
        line = line.rstrip()
        first, line = line.split('+')
        second, answer = line.split('=')

        if len(first) > 1 and first[0] == 'X':
            candidate = '123456789'
        elif len(second) > 1 and second[0] == 'X':
            candidate = '123456789'
        elif len(answer) > 1 and answer[0] == 'X':
            candidate = '123456789'
        else:
            candidate = '0123456789'

        for c in candidate:
            f = int(first.replace('X', c))
            s = int(second.replace('X', c))
            a = int(answer.replace('X', c))
            if f + s == a:
                print(c)
                break
        else:
            print('NA')
    exit()


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
while True:
	try:
		a,b,c = map(str, raw_input().replace("+","=").split("="))
		i = 1 if a!=a[0]=="X" or b!=b[0]=="X" or c!=c[0]=="X" else 0
		for x in range(i,10):
			if eval((a+"+"+b).replace("X",str(x))) == int(c.replace("X",str(x))):
				print x
				break
		else:
			print "NA"
	except:
		break

Submission status: Accepted

Solution code:
while True:
	try:
		a,b,c = map(str, raw_input().replace("+","=").split("="))
		i = 1 if a!=a[0]=="X" or b!=b[0]=="X" or c!=c[0]=="X" else 0
		for x in range(i,10):
			if eval((a+"+"+b).replace("X",str(x)))==int(c.replace("X",str(x))):
				print x
				break
		else:
			print "NA"
	except:
		break

Submission status: Accepted

Solution code:
while True:
	try:
		a,b,c = map(str, raw_input().replace("+","=").split("="))
		i = 1 if a!=a[0]=="X" or b!=b[0]=="X" or c!=c[0]=="X" else 0
		for x in range(i,10):
			if eval((a+"+"+b+"=="+c).replace("X",str(x))):
				print x
				break
		else:
			print "NA"
	except:
		break

Submission status: Accepted

Solution code:
while True:
	try:
		a,b,c = map(str,raw_input().replace("+","=").split("="))
		i = 1 if a!=a[0]=="X" or b!=b[0]=="X" or c!=c[0]=="X" else 0
		for x in range(i,10):
			if eval((a+"+"+b+"=="+c).replace("X",str(x))):
				print x
				break
		else:
			print "NA"
	except:
		break

Submission status: Accepted

Solution code:
# 文字列として入力を受け取り、Xを0～9に逐次変えてboolを取る

while 1:
    try:
        ab,s = list(input().split('='))
        a,b = list(ab.split('+'))
        start = 0
        # 第1項,第2項,結果のどれかが一桁ないし頭がXでない場合は1から始める
        if (len(a)>1 and a[0] == 'X') or (len(b)>1 and b[0] == 'X') \
            or (len(s)>1 and s[0] == 'X'): start = 1
        
        flg = 1
        for x in range (start,10):
            new_a = a.replace('X',str(x))
            new_b = b.replace('X',str(x))
            new_s = s.replace('X',str(x))
            if int(new_a)+int(new_b) == int(new_s):
                flg = 0
                print(x)
                break
        if flg: print('NA')

    except: break

Submission status: Accepted

Solution code:
for line in open(0).readlines():
    s = line.strip()
    a, s = s.split("+")
    b, c = s.split("=")
    f = lambda x: len(x) > 1 and x[0] == 'X'
    g = lambda s, x: int(s.replace("X", str(x)))
    for x in range(f(a) or f(b) or f(c), 10):
        if g(a, x) + g(b, x) == g(c, x):
            print(x)
            break
    else:
        print("NA")

Submission status: Accepted

Solution code:
import re

while True:
    try:
        s = input().strip()
    except:
        break
    var = list(re.split('[+=]', s))
    ans = -1
    for i in range(10):
        num = []
        ok = True
        for v in var:
            if i==0 and len(v)>=2 and v[0]=='X':
                ok = False
                break
            x = 0
            for j in range(len(v)):
                if v[j] == 'X':
                    x = x*10 + i
                else:
                    x = x*10 + ord(v[j])-ord('0')
            num.append(x)
        if ok:
            if num[0]+num[1] == num[2]:
                ans = i
                break
    if ans >= 0:
        print(ans)
    else:
        print('NA')

Submission status: Accepted

Solution code:
while True:
    try:
        s = input()
    except:
        break

    t, sc = s.split("=")
    sa, sb = t.split("+")

    if (len(sa) > 1 and sa[0] == 'X') \
       or (len(sb) > 1 and sb[0] == 'X') \
       or (len(sc) > 1 and sc[0] == 'X'):
        start = 1
    else:
        start = 0

    f = 0
    for i in range(start,10):
        na = int( sa.replace("X", str(i)) )
        nb = int( sb.replace("X", str(i)) )
        nc = int( sc.replace("X", str(i)) )
        if na + nb == nc:
            f += 1
            break

    if f > 0:
        print(i)
    else:
        print("NA")

Submission status: Accepted

Solution code:
import re

while True :
    try :
        Q = re.split("[+=]", input())
        A = Q[0]
        B = Q[1]
        S = Q[2]
        start = 0
        ans = "NA"
        
        if((A[0] == "X" and len(A) > 1) or (B[0] == "X" and len(B) > 1)
            or (S[0] == "X" and len(S) > 1)) :
                start = 1
                
        for i in range(start, 10) :
            a = A.replace("X", str(i))
            b = B.replace("X", str(i))
            s = S.replace("X", str(i))
            
            if(int(a) + int(b) == int(s)) :
                ans = i
                break
            else :
                pass
        
        print(ans)
        
    except :
        break

Submission status: Accepted

Solution code:
import copy
while 1:
    try:
        s = input().split('=')
        t = s[0].split('+')
        t.append(s[1])
        copy_t = copy.copy(t)
        flag = 0
        check = 0
        for i in range(3):
            if (t[i][0] == 'X' and len(t[i]) >= 2):
                check = 1
        for i in range(10):
            if check == 1 and i == 0:
                continue
            for j in range(3):
                t[j] = t[j].replace('X', str(i))
            if int(t[0]) + int(t[1]) == int(t[2]):
                flag = 1
                print(i)
                break
            t = copy.copy(copy_t)

        if flag == 0:
            print('NA')
    except:
        break

Submission status: Accepted

Solution code:
if __name__ == '__main__':

	while True:
		try:
			a,z = input().split("=")
			x,y = a.split("+")
			start = 0
			if (len(x) > 1 and x[0] == "X") or (len(y) > 1 and y[0] == "X") or (len(z) > 1 and z[0] == "X"):
				start = 1

			# x + y = zの形式に変換
			ans = False
			for i in range(start,10):
				x1 = x.replace("X",str(i))
				y1 = y.replace("X",str(i))
				z1 = z.replace("X",str(i))

				if int(x1) + int(y1) == int(z1):
					print(i)
					ans = True
					break

			if ans == False:
				print("NA")

		except EOFError:
			break

Submission status: Accepted

Solution code:
import sys

while True:
    try:
        s=input()
        ans=s.split("=")[1]
        a,b=s.split("=")[0].split("+")
        for X in range(10):
            _a=a.replace("X",str(X))
            if str(int(_a))!=_a:
                continue
            _b=b.replace("X",str(X))
            if str(int(_b))!=_b:
                continue
            _ans=ans.replace("X",str(X))
            if str(int(_ans))!=_ans:
                continue
            if int(_a)+int(_b)==int(_ans):
                print(X)
                break
        else:
            print("NA")

    except EOFError:
        sys.exit(0)

Submission status: Accepted

Solution code:
import re
while 1:
    try:N=input()
    except:break
    NUMBER=any([len(x)>1 and x[0]=='X' for x in re.split('[+=]',N)])
    N=N.replace('=','==')
    for i in '0123456789'[NUMBER:]:
        if eval(N.replace('X',i)):
            print(i)
            break
    else:print('NA')

Submission status: Accepted

Solution code:
while 1:
    try:
        l,r=map(str,input().split("="))
        l,l2=map(str,l.split("+"))
        count=0
        n=0
        if len(l)>1 and l[0]=="X" or len(l2)>1 and l2[0]=="X" or len(r)>1 and r[0]=="X":n=1
        for i in range(n,10):
            lx=l.replace("X",str(i))
            l2x=l2.replace("X",str(i))
            rx=r.replace("X",str(i))
            if int(lx)+int(l2x)==int(rx):
                print(i)
                count+=1
                break
        if count==0:print("NA")
    except:break

Submission status: Accepted

Solution code:
while True:
    try:
        s = 0
        inp = input().split("=")
        f = inp[0].split("+")
        if (len(f[0]) > 1 and f[0][0] == "X") or (len(f[1]) > 1 and f[1][0] == "X") or (len(inp[1]) > 1 and inp[1][0] == "X"):
            s = 1
        for i in range(s,10):
            left = eval(inp[0].replace("X",str(i)))
            right = int(inp[1].replace("X",str(i)))
            if left == right:
                print(i)
                break
        else:
            print("NA")
    except:
        break

Submission status: Accepted

Solution code:
while 1:
    try:
        ab, c = list(input().split("="))
    except EOFError:
        break

    a, b = list(ab.split("+"))
    start = 0
    if (a[0] == "X" and len(a) > 1) or (b[0] == "X" and len(b) > 1) or (c[0] == "X" and len(c) > 1):
        start = 1

    for i in range(start, 10):
        na = a.replace("X", str(i))
        nb = b.replace("X", str(i))
        nc = c.replace("X", str(i))

        if int(na) + int(nb) == int(nc):
            print(i)
            break
    else:
        print("NA")

Submission status: Accepted

Solution code:
def get_input():
    while True:
        try:
            yield ''.join(input())
        except EOFError:
            break


N = list(get_input())
for l in range(len(N)):


    s1,t = N[l].split('+')
    s2,s3 = t.split('=')

    ans = -1
    if (len(s1) > 1 and s1[0] == "X") or (len(s2) > 1 and s2[0] == "X") or (len(s3) > 1 and s3[0] == "X"):
        for i in range(1,10):
            n1 = int(s1.replace("X",str(i)))
            n2 = int(s2.replace("X",str(i)))
            n3 = int(s3.replace("X",str(i)))
            if n1 + n2 == n3:
                ans = i
                break
    else:
        for i in range(10):
            n1 = int(s1.replace("X",str(i)))
            n2 = int(s2.replace("X",str(i)))
            n3 = int(s3.replace("X",str(i)))
            if n1 + n2 == n3:
                ans = i
                break
    if ans >= 0:
        print(ans)
    else:
        print("NA")

Submission status: Runtime Error

Solution code:
import re
while True:
    try:
        s_origin=input()
        for X in range(10):
            s=s_origin.replace("X",str(X))
            s=s.split("=")
            s[0]=re.sub("^0+","",s[0])
            s[1]=re.sub("^0+","",s[1])
            if eval(s[0])==int(s[1]):
                print(X)
                break
        else:
            print("NA")
    except EOFError:
        break

Submission status: Runtime Error

Solution code:
X="X"
N="0123456789"
for s in sys.stdin:
  i=s.find("=")
  j=s.find("+")
  k=s[0]==X or s[i+1]==X or s[j+1]==X
  f=0
  for c in N[k:]:
    a=s.replace(X,c)
    if eval(a[:i])==eval(a[i+1:]): f=1; break
  print ["NA",c][f]

Submission status: Runtime Error

Solution code:
import re

def f(s):
    for i in range(0,10):
        t = s.replace("X", str(i))
        a, b, c = map(int, re.split(r'\+|\=', t))
        if a + b == c and str(a) + "+" + str(b) + "=" + str(c) == t:
            return i
    return "NA"

while (1):
    print f(raw_input())

Submission status: Runtime Error

Solution code:
import sys

for s in sys.stdin.readlines():
    s = s.replace('=', '==')
    flag = True
    for i in range(10):
        if i == 0:
            eight = False
            for t in s.split('X'):
                if t and (t[-1] == '+' or t[-1] == '='):
                    eight = True
                    break
            if eight:
                continue
        if eval(s.replace('X', str(i))):
            print i
            flag = False
            break
    if flag:
        print "NA"

Submission status: Runtime Error

Solution code:
for line in open('s.txt').readlines():
    n = ''
    lis = []
    for c in line.rstrip():
        if c.isdigit() or c == 'X':
            n += c
        elif c == '+':
            lis.append(n)
            n = ''
        elif c == '=':
            lis.append(n)
            n = ''
    else:
        lis.append(n)
     
    c_lis = lis[:]   
    for n in range(10):
        for i, v in enumerate(lis):
            if 'X' in v:
                c_lis[i] = c_lis[i].replace('X', str(n))
        else:
            flag = False
            if n == 0:
                for v in c_lis:
                    if len(v) >= 2 and v[0] == '0':
                        flag = True
                        break
            if not flag:
                if int(c_lis[0]) + int(c_lis[1]) == int(c_lis[2]):
                    print n
                    break
            c_lis = lis[:]
    else:
        print 'NA'

Submission status: Runtime Error

Solution code:
import sys
def line():return sys.stdin.readline().strip()

import re

while True:
    e = re.findall(r"[0-9X]+",line())

    ans = -1
    for i in range(10):
        a,b,c = [int(_.replace("X",str(i))) for _ in e]
        if a + b == c :
            ans = i
            break

    if ans == -1:
        print("NA")
    else:
        print(ans)

Submission status: Runtime Error

Solution code:
import sys
import re
def line():return sys.stdin.readline().strip()

while True:

    e = re.findall(r"[0-9X]+",line())

    ans = -1
    for i in range(10):
        a,b,c = [int(_.replace("X",str(i))) for _ in e]
        if a + b == c :
            ans = i
            break

    if ans == -1:
        print("NA")
    else:
        print(ans)

Submission status: Runtime Error

Solution code:
while True:
    try:
        dataset = input()
    except:
        break
    flag = True
    for i in range(10):
        sequence = dataset.replace("=", "+").split("+")
        if i == 0 and any([True if seq[0]=="X" and len(seq) >= 2 else False for seq in sequence]):
            continue
        a, b, c = map(int, [seq.replace("X", str(i)) for seq in sequence[:2]]), sequence[2].replace("X", str(i))
        if a+b == c:
            print(i)
            flag = False
            break
    if flag:
        print("NA")

Submission status: Runtime Error

Solution code:
import sys

for line in sys.stdin:
    src = line.strip().replace('=','==')
    res = "NA"
    for i in range(10):
        if eval(src.replace('X',str(i))):
            res = str(i)
            break;
    print(res)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
"""
import sys


def solve(exp):
    for i in range(10):
        modified_exp = exp.replace('X', str(i))
        left, right = modified_exp.split('=')
        left = left.lstrip('0')
        right = right.lstrip('0')
        if eval(left) == eval(right):
            return i
    return 'NA'


def main(args):
    for line in sys.stdin:
        result = solve(line)
        print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
"""
import sys
import re

def solve(exp):
    p1 = re.compile('^0+')
    p2 = re.compile('\+0')
    for i in range(10):
        modified_exp = exp.replace('X', str(i))
        left, right = modified_exp.split('=')
        left = p1.sub('', left)
        left = p2.sub('+', left)
        right = p1.sub('', right)
        right = p2.sub('+', right)
        if eval(left) == eval(right):
            return i
    return 'NA'


def main(args):
    for line in sys.stdin:
        result = solve(line.strip())
        print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0110
"""
# runtime error
import sys
import re

def solve(exp):
    p1 = re.compile('^0+')
    for i in range(10):
        modified_exp = exp.replace('X', str(i))
        left, right = modified_exp.split('=')
        left1, left2 = left.split('+')

        if len(left1) > 1:
            left1 = p1.sub('', left1)
        if len(left2) > 1:
            left2 = p1.sub('', left2)
        if len(right) > 1:
            right = p1.sub('', right)

        if int(left1)+int(left2)==int(right):
            return i
    return 'NA'


def main(args):
    for line in sys.stdin:
        result = solve(line.strip())
        print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
import sys
t='X'
for e in sys.stdin:
 for i in'0123456789'[(e[0]==t)*(e[1]!='+')or('+X'in e)*('+X='not in e)or('=X'in e)*(e[-1]==t):]:
  if eval(e.replace(t,i).replace('=','==')):print(i);break
 else:print('NA')

Submission status: Runtime Error

Solution code:
import sys
t='X'
for e in sys.stdin:
 for i in'0123456789'[(e[0]==t)*('+'!=e[1])or('+X'in e)*('+X='not in e)or('=X'in e)*(e[-1]==t):]:
  if eval(e.replace(t,i).replace('=','==')):print(i);break
 else:print('NA')

Submission status: Runtime Error

Solution code:
import sys
t='X'
for e in sys.stdin:
 for i in'0123456789'[(e[0]==t)*('+'!=e[1])or('+X'in e)*('+X='not in e)or('=X'in e)*(e[-2]=='='):]:
  if eval(e.replace(t,i).replace('=','==')):print(i);break
 else:print('NA')

Submission status: Runtime Error

Solution code:
import sys
t='X'
for e in sys.stdin:
 for i in'0123456789'[(e[0]==t)*(e[1]!='+')or('+X'in e)*not('+X='in e)or('=X'in e)*(e[-2]!='='):]:
  if eval(e.replace(t,i).replace('=','==')):print(i);break
 else:print('NA')

Submission status: Runtime Error

Solution code:
import sys
t='X'
for e in sys.stdin:
 for i in'0123456789'[(e[0]==t)*(e[1]!='+')or('+X'in e)*('+X='not in e)or(e[-2:]=='=X'):]:
  if eval(e.replace(t,i).replace('=','==')):print(i);break
 else:print('NA')

Submission status: Runtime Error

Solution code:
import re
for e in sys.stdin:
    s=any([len(x)>1 and x[0]=='X' for x in re.split('[+=]',e)])
    for i in '0123456789'[s:]:
        if eval(e.replace('X',i).replace('=','==')):print(i);break
    else:print('NA')

Submission status: Runtime Error

Solution code:
import sys
for e in sys.stdin:
 for i in'0123456789'[(e[0]==t)*(e[1]!='+')or('+X'in e)*('+X='not in e)or('=X'in e):]:
  l,r=e.replace('X',i).split('=')
  if sum(map(int,l.split('+')))==int(r):print(i);break
 else:print('NA')

Submission status: Runtime Error

Solution code:
import re,sys
def chk(t):
    for i in range(10):
        if eval(re.sub("X",str(i),t)):
            return i
    return 10

l=[chk(i.replace("=","==")) for i in sys.stdin]
[print(i) if i != 10 else print("NA") for i in l]

Submission status: Runtime Error

Solution code:
def form_check(t):
    plus = t.index('+')
    equal = t.index('=')
    if len(t[:plus]) > 1 or len(t[plus + 1:equal]) > 1 or len(t[equal + 1:]  > 1):
        return False
    return True

def check(t):
    equal = t.index('=')
    if eval(t[:equal]) == eval(t[equal + 1:]):
        return True
    else:
        return False

while True:
    try:
        line = raw_input()
    except EOFError:
        break

    if form_check(line):
        nums = range(0, 10)
    else:
        nums = range(1, 10)
    a = -1
    for num in nums:
        if check(line.replace('X', str(num))):
            a = num
    if a >= 0:
        print a
    else:
        print 'NA'

Submission status: Runtime Error

Solution code:
import sys
for line in sys.stdin.readlines():
    a="NA"
    for i in xrange(10):
        exp,ans=line.strip().replace("X",str(i)).split("=")
        if eval(exp)==int(ans):
            a=i
    print a

Submission status: Runtime Error

Solution code:

import sys


def solv(s):
    left, right = s.split('=')
    for i in range(10):
        l = left.replace('X', str(i))
        r = right.replace('X', str(i))
        if eval(l) == int(r):
            return str(i)
    else:
        return 'NA'


for line in sys.stdin:
    print solv(line.rstrip('\n'))

Submission status: Runtime Error

Solution code:

import sys


def solv(s):
    left, right = s.split('=')
    for i in range(10):
        l = left.replace('X', str(i))
        r = right.replace('X', str(i))
        l1, l2 = l.split('+')
        if l1[0] == '0' or l2[0] == '0' or r[0] == '0':
            next
        if eval(l) == int(r):
            return str(i)
    else:
        return 'NA'


for line in sys.stdin:
    print solv(line.rstrip('\n'))

Submission status: Runtime Error

Solution code:

import sys


def solv(s):
    left, right = s.split('=')
    for i in range(10):
        i = str(i)
        l = left.replace('X', i)
        r = right.replace('X', i)
        l1, l2 = l.split('+')
        if l1[0] == '0' or l2[0] == '0' or r[0] == '0':
            next
        if eval(l) == int(r):
            return i
    else:
        return 'NA'


for line in sys.stdin:
    print solv(line.rstrip('\n'))

Submission status: Runtime Error

Solution code:

import sys


def solv(s):
    left, right = s.split('=')
    for i in range(10):
        i = str(i)
        l = left.replace('X', i)
        r = right.replace('X', i)
#        l1, l2 = l.split('+')
#        if i == '0' and (l1[0] == '0' or l2[0] == '0' or r[0] == '0'):
#            continue
        if eval(l) == int(r):
            return i
    else:
        return 'NA'


for line in sys.stdin:
    print solv(line.rstrip('\n'))