#39342: (python)TLE,求救


peter26 (瑪卡巴卡)

學校 : 基隆市私立二信高級中學
編號 : 260646
來源 : [210.71.40.1]
最後登入時間 :
2024-11-21 14:45:28
a017. 五則運算 | From: [111.248.250.134] | 發表日期 : 2024-02-08 04:45

def math( sentence ):
    if len(sentence) == 1:
        return sentence[0]
    while '(' in sentence:
        u1 = sentence.index('(')
        u2 = sentence.index(')')
        if '(' in sentence[(u2 -u1)//2:u2]:
            if '(' in sentence[(u2 -u1)//4:u2]:
                for i in range((u2 -u1)//4, u2):
                    if sentence[i] == '(':
                        u1 = i
            else:
                for i in range((u2 -u1)//2, (u2 -u1)//4):
                    if sentence[i] == '(':
                        u1 = i
        else:
            if '(' in sentence[(u2 -u1)//4:(u2 -u1)//2]:
                for i in range((u2 -u1)//4, (u2 -u1)//2):
                    if sentence[i] == '(':
                        u1 = i
            else:
                for i in range(u1, (u2 -u1)//4):
                    if sentence[i] == '(':
                        u1 = i
        sentence[u1] = math(sentence[u1+1:u2])
        del sentence[u1+1:u2+1]
    if len({'*', '/', '%'} & set(sentence)) > 0:
        array = list({'*', '/', '%'} & set(sentence))
        array = [sentence.index(i) for i in array]
        yeah = min( array )
        if sentence[yeah] == '*':
            sentence[yeah-1] = sentence[yeah-1] * sentence[yeah+1]
            del sentence[yeah:yeah+2]
            return math(sentence)
        if sentence[yeah] == '/':
            if sentence[yeah+1] == 0:
                return '北七'
            sentence[yeah-1] = sentence[yeah-1] // sentence[yeah+1]
            del sentence[yeah:yeah+2]
            return math(sentence)
        if sentence[yeah] == '%':
            sentence[yeah-1] = sentence[yeah-1] % sentence[yeah+1]
            del sentence[yeah:yeah+2]
            return math(sentence)
    if sentence[1] == '+':
        sentence[2] = sentence[0] + sentence[2]
        del sentence[:2]
        return math(sentence)
    if sentence[1] == '-':
        sentence[2] = sentence[0] - sentence[2]
        del sentence[:2]
        return math(sentence)

while True:
    try:
        sentence = input().split()
        for i in range(len(sentence)):
            try:
                sentence[i] = int( sentence[i] )
            except:
                continue
        print(math(sentence))
    except:
        pass
 
ZeroJudge Forum