import re
tmp = []
calculate = []
cnt = 0
data = input()
numbers = re.findall('\d+',data)
if len(numbers) >= 2:
for i in range(0, len(numbers)):
if len(numbers[i]) >= 2:
if numbers[i][0] == '0':
numbers[i] = numbers[i][1:len(numbers)]
for d in data:
if d == '+':
tmp.append(int(numbers[cnt]) + int(numbers[cnt + 1]))
calculate.append('+')
cnt += 1
elif d == '-':
tmp.append(int(numbers[cnt]))
calculate.append('-')
cnt += 1
if calculate[-1] == '-':
tmp.append(int(numbers[-1]))
if len(tmp) == 1:
print(tmp[0])
else:
result = tmp[0]
for i in range(1, len(tmp)):
result -= tmp[i]
print(result)
else:
print(numbers[0])
55+50+40-30 처럼 +가 두번 나오는 경우를 생각하지 못했다.
import re
tmp = []
calculate = []
data = input()
numbers = re.findall('\d+',data)
pluscnt = 0
minuscnt = 0
if len(numbers) >= 2:
for i in range(0, len(numbers)):
if len(numbers[i]) >= 2:
if numbers[i][0] == '0':
numbers[i] = numbers[i][1:len(numbers)]
for d in data:
if d == '+':
if pluscnt == 0:
a = numbers.pop(0)
b = numbers.pop(0)
tmp.append(int(a) + int(b))
else:
tmp[minuscnt] = tmp[minuscnt] + int(numbers.pop(0))
calculate.append('+')
pluscnt += 1
elif d == '-':
tmp.append(int(numbers.pop(0)))
calculate.append('-')
minuscnt += 1
if (minuscnt > 1) and (calculate[-1] == '-'):
tmp.append(int(numbers[-1]))
if len(tmp) == 1:
print(int(tmp[0]))
else:
result = tmp[0]
for i in range(1, len(tmp)):
result -= tmp[i]
print(result)
else:
print(int(numbers[0]))
런타임 에러 발생
data = input().split('-')
result = 0
for i in data[0].split('+'):
result += int(i)
for i in data[1:]:
for j in i.split('+'):
result -= int(j)
print(result)
너무 복잡하게 생각했다. '+'와 '-'를 기준으로 split해주면 간단하게 해결되는 문제였다.