Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Broken Cipher Generator
-->

壊れた暗号生成器

JAG (Japanese Alumni Group) は多くのプログラマで構成される謎の組織であり，この組織の本部がある建物に入るためには毎回ある機械によって生成される暗号文を解かなくてはならない．
この暗号文は，'+'，'-'，'['，']' の記号と大文字のアルファベットからなっており，以下の BNF で定義される <Cipher> によって表される．

<Cipher> ::= <String> | <Cipher><String>
<String> ::= <Letter> | '['<Cipher>']'
<Letter> ::= '+'<Letter> | '-'<Letter> |
             'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' |
             'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'

ここでそれぞれの記号は以下のような意味を表す．

 +(文字) : その文字の次のアルファベットを表す (ただし 'Z' の次のアルファベットは 'A' であるとする)

 -(文字) : その文字の前のアルファベットを表す (ただし 'A' の前のアルファベットは 'Z' であるとする)

 [(文字列)] : その文字列を左右反転した文字列を表す

しかしこの暗号文を生成する機械には現在故障が発生しており，暗号文のうちアルファベットの箇所が数文字壊れて読めなくなっている場合がある．読めない文字は仮に '?' と表されている．
調査の結果，壊れた文字の埋め方は，復号後の文字列が，復号後の文字列としてありえる文字列の中で辞書順最小になるようなものであることがわかった．
あなたの仕事はこの暗号文を正しく復号することである．

Input

入力は複数のデータセットから構成される．
各データセットは，上記の BNF で定義された暗号文において，一部の大文字のアルファベットが ‘?’ に置き換えられた文字列を含む 1 行からなる．
各文字列の長さは $80$ 以下であると仮定してよい．
また各データセットに含まれる '?' の数は $0$ 以上 $3$ 以下であると仮定してよい．

入力の終了は '.' の1文字だけを含む行で表される．

Output

各データセットに対して，復号後の文字列が辞書順最小になるように暗号文を復号したときの，復号後の文字列を出力せよ．

Sample Input

A+A++A
Z-Z--Z+-Z
[ESREVER]
J---?---J
++++++++A+++Z-----------A+++Z
[[++-+--?[--++-?++-+++L]][-+-----+-O]]++++---+L
.

Output for Sample Input

ABC
ZYXZ
REVERSE
JAG
ICPC
JAPAN



Sample input:
A+A++A
Z-Z--Z+-Z
[ESREVER]
J---?---J
++++++++A+++Z-----------A+++Z
[[++-+--?[--++-?++-+++L]][-+-----+-O]]++++---+L
.


Sample output:
ABC
ZYXZ
REVERSE
JAG
ICPC
JAPAN

Submission status: Accepted

Solution code:
import re
bracket = re.compile(r'\[([\w?+-]+)\]')
incr = re.compile(r'([+-]*)([\w?])')

def f(s, c):
    if c == '?': return 'A'
    return chr(ord('A')+(ord(c)-ord('A')+s.count('+')-s.count('-'))%26)

while True:
    s = input().strip()
    if s == '.': break

    s = incr.sub(lambda m: f(*m.group(1, 2)), s)
    while '[' in s:
        s = bracket.sub(lambda m: m.group(1)[::-1], s)

    print(s)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def _kosa(a1, a2, b1, b2):
    x1,y1,_ = a1
    x2,y2,_ = a2
    x3,y3,_ = b1
    x4,y4,_ = b2

    tc = (x1-x2)*(y3-y1)+(y1-y2)*(x1-x3)
    td = (x1-x2)*(y4-y1)+(y1-y2)*(x1-x4)
    return tc*td < 0

def kosa(a1, a2, b1, b2):
    return _kosa(a1,a2,b1,b2) and _kosa(b1,b2,a1,a2)


def distance(x1, y1, x2, y2):
    return math.sqrt((x1-x2)**2 + (y1-y2)**2)

def distance3(p1, p2, p3):
    x1,y1,_ = p1
    x2,y2,_ = p2
    x3,y3,_ = p3

    ax = x2 - x1
    ay = y2 - y1
    bx = x3 - x1
    by = y3 - y1

    r = (ax*bx + ay*by) / (ax*ax+ay*ay)
    if r <= 0:
        return distance(x1,y1, x3,y3)
    if r >= 1:
        return distance(x2,y2, x3,y3)
    return distance(x1 + r*ax, y1 + r*ay, x3,y3)

def main():
    rr = []

    def f(s):
        def _f(s):
            if '[' in s:
                i = s.index('[')
                c = 1
                for j in range(i+1,len(s)):
                    if s[j] == '[':
                        c += 1
                    elif s[j] == ']':
                        c -= 1
                        if c == 0:
                            return _f(s[:i] + _f(s[i+1:j])[::-1] + s[j+1:])
                return -1
            r = ''
            c = 0
            for t in s:
                if t == '-':
                    c -= 1
                elif t == '+':
                    c += 1
                elif t == '?':
                    r += 'A'
                    c = 0
                else:
                    o = ord(t) - ord('A')
                    o += c
                    o %= 26
                    r += chr(o + ord('A'))
                    c = 0
            return r

        return _f(s)


    while True:
        s = S()
        if s == '.':
            break
        rr.append(f(s))

    return '\n'.join(map(str, rr))



print(main())

Submission status: Accepted

Solution code:
import re

bra_re = re.compile(r'\[([-+\w?]+)\]')
let_re = re.compile(r'[-+]*[\w?]')

def rep(m):
    s = m.group(0)
    if s[-1] == '?': return 'A'
    d = 0
    d += s.count('+')
    d -= s.count('-')
    d %= 26
    d += ord(s[-1])
    if d < ord('A'): d += 26
    if d > ord('Z'): d -= 26
    return chr(d)

def dec(m):
    s = m.group(1)
    return let_re.sub(rep, s)[::-1]

def decipher(s):
    m = bra_re.search(s)
    while m is not None:
        s = bra_re.sub(dec, s)
        m = bra_re.search(s)

    s = let_re.sub(rep, s)
    print(s)

while True:
    s = input()
    if s == '.': break
    decipher(s)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
let = [chr(i) for i in xrange(ord('A'), ord('Z') + 1)]

def reverse(s, pos):
    res, rev = "", ""
    p = 0
    while p < len(s):
        if s[p] == '[':
            hoge, p = reverse(s[p + 1:], p + 1)
            rev += hoge
        elif s[p] == ']':
            return rev[::-1], p + pos
        else:
            rev += s[p]
        p += 1

def letter(s):
    stack = 0
    tmp = ""
    for i in s:
        if i == '+':stack += 1
        if i == '-':stack -= 1
        if ord('A') <= ord(i) and ord(i) <= ord('Z'):
            tmp += let[(ord(i) - ord('A') + stack + 26*30)%26]
            stack = 0
        if i == '?':
            tmp += 'A'
            stack = 0
        if i == '[' or i == ']':
            tmp += i
    res = ""
    p = 0
    while p < len(tmp):
        if tmp[p] == '[':
            hoge, p = reverse(tmp[p + 1:], p + 1)
            res += hoge
        elif tmp[p] != ']':
            res += tmp[p]
        p += 1;
    return res

def __main__():
    while 1:
        s = raw_input()
        if s == ".":break
        print letter(s)


__main__()

Submission status: Accepted

Solution code:
alps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def reverse(data):
    ret = ""
    while(True):
        if data[0] == "[" and (not ("[" in data[1:]) or data.index("[") > data.index("]")):
            tmp = data[1:data.index("]")][::-1]
            ret += tmp
            ret += data[data.index("]")+1:]
            return(ret)
        else:
            ret += data[0]
            data = data[1:]

while(True):
    a = input()
    if a == ".":
        quit()
    ans = ""
    plus = 0
    count = 0
    while(a != ""):
        if a[0] in ["[","]"]:
            ans += a[0]
            plus = 0
            count += 1
        elif a[0] == "?":
            ans += "A"
            plus = 0
        elif a[0] == "+":
            plus += 1
        elif a[0] == "-":
            plus -= 1
        else:
            t = alps.index(a[0])
            ans += alps[(t + plus)%26]
            plus = 0
        a = a[1:]
    count //= 2
    indl = [i for i, x in enumerate(a) if x == "["]
    indr = [i for i, x in enumerate(a) if x == "]"]
    for i in range(count):
        ans = reverse(ans)
    print(ans)

Submission status: Accepted

Solution code:
pos = 0
s = ""
def read():
    global pos
    global s

    result = ""
    ruiseki = 0
    while pos < len(s):
        if s[pos] == '+':
            ruiseki += 1
        elif s[pos] == '-':
            ruiseki -= 1
        elif s[pos] == '[':
            pos += 1
            result += read()
            pos -= 1
        elif s[pos] == ']':
            pos += 1
            return result[::-1]
        elif s[pos] == '?':
            result += 'A'
            ruiseki = 0
        else:
            order = ord(s[pos]) + ruiseki
            while order < 65:
                order += 26
            while order > 90:
                order -= 26
            result += chr(order)
            ruiseki = 0

        pos += 1

    return result


while True:
    pos = 0
    s = input()
    if s == ".":
        break

    print(read())

Submission status: Accepted

Solution code:
#!/usr/bin/env python

from collections import deque
import itertools as it
import sys

sys.setrecursionlimit(1000000)

def rev(S):
    return S[::-1]

def add(S):
    if S[0] == '?':
        return S
    lst = list(S)
    lst[0] = chr((ord(S[0]) - ord('A') + 1) % 26 + ord('A'))
    return ''.join(lst)

def dec(S):
    if S[0] == '?':
        return S
    lst = list(S)
    lst[0] = chr((ord(S[0]) - ord('A') - 1) % 26 + ord('A'))
    return ''.join(lst)

while True:
    S = raw_input()
    if S == '.':
        break
    ans = ''
    cnt = 0
    f_lst = []
    for c in S:
        if c == '+':
            ans += 'add('
            f_lst.append('add')
        elif c == '-':
            ans += 'dec('
            f_lst.append('dec')
        elif c == '[':
            ans += 'rev('
            f_lst.append('rev')
        else:
            if c == ']':
                ans = ans[:-1]
                while len(f_lst) > 0:
                    f = f_lst.pop()
                    ans += ')'
                    if f == 'rev':
                        break
            else:
                ans += "'" + c + "'"
                while len(f_lst) > 0:
                    f = f_lst.pop()
                    if f == 'rev':
                        f_lst.append('rev')
                        break
                    ans += ')'
            ans += '+'
    ans = ans[:-1]
    ret = eval(ans)
    print ret.replace('?', 'A')

Submission status: Accepted

Solution code:
def c_to_int(char):
    return ord(char)-65

def solve(s):
    count = 0
    table=[]
    for str in s:
        if str=='+':
            count +=1
        elif str =='-':
            count -=1
        elif str=='[':
            table.append(str)
        elif str==']':
            table.append(str)
        elif str=='?':
            table.append(str)
            count =0
        else:
            table.append((c_to_int(str) +count)%26)
            count = 0

    for i in range(len(table)):
        if table[i]=='?':
            table[i] = 0
#    print(table)
    return(table)

def rev(table):
    ret = "" 
    i =0
    while i <  len(table):
        if table[i] == '[':
            c  = 1
            i_=i+1
            while c>0:
                if table[i_] =='[':
                    c += 1
                if table[i_] ==']':
                    c -= 1
                i_ += 1
 #           print(reversed(table[i+1:i_-1]))
            ret += rev(table[i+1:i_-1])[::-1]
            i = i_-1
        elif table[i] ==']':
            pass
        else:
#            print(chr(table[i]+65))
            ret += chr(table[i]+65)
        i+=1

    return ret


while True:
    S = input()
    if S[0]=='.':
        break
    ans = rev(solve(S))
    print(ans)

Submission status: Accepted

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        if s.find('+') == -1 and s.find('-') == -1:
            index = s.rfind('[')
            if index == -1:
                break
            e = s[index:].find(']')
            s = s[:index] + s[index + 1:index + e][::-1] + s[index + e + 1:]
        else:
            if s.find('+') != -1:
                index = s.find('+')
            if s.find('-') != -1:
                if s.find('+') != -1:
                    index = min(index, s.find('-'))
                else:
                    index = s.find('-')
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                if s[e] == '+':
                    f += 1
                else:
                    f -= 1
                e += 1
            r = s[e]
            if r != '?':
                r = chr((ord(r) - ord('A') + f) % 26 + ord('A'))
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?', 'A'))

Submission status: Accepted

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        if s.find('+') == -1 and s.find('-') == -1:
            index = s.rfind('[')
            if index == -1:break
            e = s.find(']', index, len(s))
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            index = s.find('+')
            if index == -1:
                index = s.find('-')
            if s.find('-') != -1:
                index = min(index, s.find('-'))
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                f += [-1, 1][s[e] == '+']
                e += 1
            r = s[e]
            if r != '?':
                r = chr((ord(r) - ord('A') + f) % 26 + ord('A'))
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?', 'A'))

Submission status: Accepted

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        if s.find('+') == -1 and s.find('-') == -1:
            index = s.rfind('[')
            if index == -1:break
            e = s.find(']', index)
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            index = s.find('+')
            if index == -1:
                index = s.find('-')
            if s.find('-') != -1:
                index = min(index, s.find('-'))
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                f += [-1, 1][s[e] == '+']
                e += 1
            r = s[e]
            if r != '?':
                r = chr((ord(r) - ord('A') + f) % 26 + ord('A'))
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?', 'A'))

Submission status: Accepted

Solution code:
def pm_to_chr(s):
    s=s.group()
    if s[-1]=='?':
        return 'A'
    ans=chr((((ord(s[-1])+s.count('+')-s.count('-'))-ord('A'))%26)+ord('A'))
    return ans

def reverse(s):
    s=s.group()
    s=s[1:-1]
    ans=''.join(reversed(s))
    return ans

import re

s=input()
while s!='.':
    s=re.sub("[\+\-]*[\w?]",pm_to_chr,s)
    while('[' in s):
        s=re.sub("\[\w+\]",reverse,s)
    print(s)
    s=input()

Submission status: Accepted

Solution code:
import sys
from itertools import product
from collections import deque
read = sys.stdin.read
def enc(S:str, p:int):
    return chr((ord(S) + p - ord("A")) % 26  + ord("A")) 
def f(S:str):
    res = []
    plus_minus = 0
    # q = deque()
    stack = []
    for s in S:
        if("A" <= s <= "Z"):
            s = enc(s, plus_minus)
            plus_minus = 0
            res.append(s)
        elif s=="-":
            plus_minus-=1
        elif s=="+":
            plus_minus+=1
        elif s=="[":
            stack.append(len(res))
        else:
            if not stack:
                return None
            rev_i = stack.pop()
            res[rev_i:] = res[rev_i:][::-1]

    if(stack or plus_minus):
        raise Exception
        return None
    return "".join(res)
def solve(S:str):
    ans = "Z"*len(S)
    L = [chr(ord("A") + i) for i in range(26)]
    for it in product(L, repeat=S.count("?")):
        *it, = it
        # print(it)
        idx = 0
        T = ""
        for s in S:
            if(s == "?"):
                T += it[idx]
                idx += 1
            else:
                T += s
        res = f(T)
        if(res is None):
            continue
        # print(res)
        # if(S == "[[++-+--?[--++-?++-+++L]][-+-----+-O]]++++---+L"):
        #     print(res)
        ans = min(ans, res)
    print(ans)
def main():
    
    S = read()
    for s in S.split("\n"):
        if(s=="."):
            break
        solve(s)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import string
dic_str = {}
for i,item in enumerate(string.ascii_uppercase):
  dic_str[item] = i
"""
def rev(lis,bl = False):
  if not "[" in lis:
    return "".join(lis)
  else:
    start = -1
    end = -1
    i = 0
    while(i < len(lis)):
      if (start == -1) and (lis[i] == "["):
        start = i
      if (start != -1) and (lis[i] == "]"):
        end = i
        break
      i += 1
    print(start,end)
    return rev(list("".join(lis[0:start])+rev(lis[start+1:end],True)+"".join(lis[end+1:len(lis)+1])))
"""

  
while(True):
  strs = input()
  
  if strs == ".":
    break
  lis_str = list(strs)
  change_alpha = []
  count = 0
  i = 0
  while(i < len(lis_str)):
    if lis_str[i] in list(string.ascii_uppercase):
      change_alpha.append(string.ascii_uppercase[(dic_str[lis_str[i]]+count)%26])
      count = 0
    elif lis_str[i] == "?":
      change_alpha.append("A")
      count = 0
    elif lis_str[i] == "+":
      count += 1
    elif lis_str[i] == "-":
      count -= 1
    elif (lis_str[i] == "[") or (lis_str[i] == "]"):
      change_alpha.append(lis_str[i])
    i += 1
    
  i = 0
  start = -1
  end = -1
  while(i < len(change_alpha)):
    if change_alpha[i] == "[":
      start = i
      i += 1
    elif change_alpha[i] == "]":
      end = i
      #print(change_alpha)
      #print(change_alpha[start+1:end])
      #print(list(reversed(change_alpha[start+1:end])))
      change_alpha[start+1:end] = list(reversed(change_alpha[start+1:end]))
      #print(change_alpha)
      change_alpha.pop(start)
      change_alpha.pop(end-1)
      start = -1
      end = -1
      i = 0
    else:
      i += 1
  else:
    print("".join(change_alpha))

Submission status: Accepted

Solution code:
import string
abc = string.ascii_uppercase

while True:
  s = input()
  if s==".":
    break

  num = 0
  rev = 0
  nest = ["" for i in range(80)]

  for e in s:
    if e=="+":
      num += 1
    elif e=="-":
      num -= 1
    elif e=="[":
      rev += 1
    elif e=="]":
      t = nest[rev]
      nest[rev-1] += t[::-1]
      nest[rev] = ""
      rev -= 1
    elif e=="?":
      nest[rev] += "A"
      num = 0
    else:
      t = abc[(ord(e)+num-65)%26]
      nest[rev] += t
      num = 0
  print(nest[0])

Submission status: Accepted

Solution code:
import re
while 1:
    s=input()
    if s==".":break
    while "+-" in s or "-+" in s:
        s=s.replace("+-","").replace("-+","")
    while "+" in s:
        pos=s.rfind("+")
        cha=s[pos]+s[pos+1]
        if ord(s[pos+1])==90:cha_r="A"
        elif ord(s[pos+1])==63:cha_r="?"
        else:cha_r=chr(ord(s[pos+1])+1)
        s=s.replace(cha,cha_r)
    while "-" in s:
        pos=s.rfind("-")
        cha=s[pos]+s[pos+1]
        if ord(s[pos+1])==65:cha_r="Z"
        elif ord(s[pos+1])==63:cha_r="?"
        else:cha_r=chr(ord(s[pos+1])-1)
        s=s.replace(cha,cha_r)
    while "[" in s:
        match = re.search(r'\[[A-Z\?]+\]',s)
        cha=match.group(0)
        cha_r=cha[::-1][1:-1]
        s=s.replace(cha,cha_r)
    while "?" in s:
        s=s.replace("?","A")
    print(s)

Submission status: Accepted

Solution code:
def make(s):
    d=[]
    i=0
    ans=''
    while i<len(s):
        if s[len(s)-i-1] not in '+-[]':
            d.append(ord(s[len(s)-i-1]))
        else:
            if s[len(s)-i-1] == '+':
                if d[-1]!=ord('?'):
                    d[-1]=((d[-1]+1)-ord('A'))%26+ord('A')
            elif s[len(s)-i-1] == '-':
                if d[-1]!=ord('?'):
                    d[-1]=((d[-1]-1)-ord('A'))%26+ord('A')
            else:
                end=len(s)-i-1
                st=len(s)-i-2
                p=1
                while 1:
                    if s[st]==']':
                        p+=1
                    elif s[st]=='[':
                        p-=1
                    if p==0:
                        for j in range(len(d)):
                            ans+=chr(d[j])
                        ans+=make(s[st+1:end])
                        d=[]
                        i=len(s)-st-1
                        break
                    st-=1
        i+=1
    for j in range(len(d)):
        ans+=chr(d[j])
    return ans[::-1]

while 1:
    s=input()
    if s=='.':
        break
    for c in make(s):
        print('A' if c=='?' else c,end='')
    print()

Submission status: Runtime Error

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        index = min(max(0, s.find('+')), max(0, s.find('-')))
        if index == 0 and s[0] != '+' and s[0] != '-':
            index = s.rfind('[')
            if index == -1:
                break
            e = s[index:].find(']')
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                e += 1
                if s[e] == '+':
                    f += 1
                else:
                    f -= 1
            r = s[e]
            if s[e] != '?':
                r = chr(ord(r) += f)
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?','A'))

Submission status: Runtime Error

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        index = min(max(0, s.find('+')), max(0, s.find('-')))
        if index == 0 and s[0] != '+' and s[0] != '-':
            index = s.rfind('[')
            if index == -1:
                break
            e = s[index:].find(']')
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                e += 1
                if s[e] == '+':
                    f += 1
                else:
                    f -= 1
            r = s[e]
            if r != '?':
                r = chr(ord(r) += f)
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?','A'))

Submission status: Runtime Error

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        index = min(max(0, s.find('+')), max(0, s.find('-')))
        if index == 0 and s[0] != '+' and s[0] != '-':
            index = s.rfind('[')
            if index == -1:
                break
            e = s[index:].find(']')
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                e += 1
                if s[e] == '+':
                    f += 1
                else:
                    f -= 1
            r = s[e]
            if r != '?':
                r = chr(ord(r) + f)
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?','A'))

Submission status: Runtime Error

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        index = min(max(0, s.find('+')), max(0, s.find('-')))
        if index == 0 and s[0] != '+' and s[0] != '-':
            index = s.rfind('[')
            if index == -1:
                break
            e = s[index:].find(']')
            s = s[:index] + s[index + 1:index + e][::-1] + s[index + e + 1:]
        else:
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                e += 1
                if s[e] == '+':
                    f += 1
                else:
                    f -= 1
            r = s[e]
            if r != '?':
                r = chr(ord(r) + f)
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?','A'))

Submission status: Runtime Error

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        index = min(max(0, s.find('+')), max(0, s.find('-')))
        if index == 0 and s[0] != '+' and s[0] != '-':
            index = s.rfind('[')
            if index == -1:
                break
            e = s[index:].find(']')
            s = s[:index] + s[index + 1:index + e][::-1] + s[index + e + 1:]
        else:
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                if s[e] == '+':
                    f += 1
                else:
                    f -= 1
                e += 1
            r = s[e]
            if r != '?':
                r = chr(ord(r) + f)
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?', 'A'))

Submission status: Runtime Error

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        if s.find('+') == -1 and s.find('-') == -1:
            index = s.rfind('[')
            if index == -1:break
            e = s.find(']', index)
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            index = s.find('+')
            if index == -1:
                index = s.find('-')
            if s.find('-') != -1
                index = min(index, s.find('-'))
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                f += [-1, 1][s[e] == '+']
                e += 1
            r = s[e]
            if r != '?':
                r = chr((ord(r) - ord('A') + f) % 26 + ord('A'))
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?', 'A'))

Submission status: Runtime Error

Solution code:
while True:
    s = input()
    if s == '.':break
    while True:
        if s.find('+') == -1 and s.find('-') == -1:
            index = s.rfind('[')
            if index == -1:break
            e = s.find(']', index, len(s))
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            index = s.find('+')
            if index == -1:
                index = s.find('-')
            if s.find('-') != -1
                index = min(index, s.find('-'))
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                f += [-1, 1][s[e] == '+']
                e += 1
            r = s[e]
            if r != '?':
                r = chr((ord(r) - ord('A') + f) % 26 + ord('A'))
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?', 'A'))