【每日一题1115】等式反转

:mage:t2: 给定一个包含+, -, *, /的数学运算表达式,请编写一个函数,将其中的运算符的顺序进行反转。

示例:
输入: "100*b/y",输出: "y/b*100"
输入: "a+b-c/d*30",输出: "30*d/c-b+a"

题目难度:简单
题目来源:codewars

def solution(equation: str) -> str:
    pass

assert solution("100*b/y") == "y/b*100"
assert solution("a+b-c/d*30") == "30*d/c-b+a"
assert solution("a*b/c+50") == "50+c/b*a"
def solution(equation: str) -> str:
    one_str = ''
    eq_list = []
    for i in equation + '+':
        if i not in ['*', '/', '+', '-']:
            one_str += i
        else:
            eq_list.append(one_str)
            eq_list.append(i)
            one_str = ''
    eq_list.pop()
    return ''.join(eq_list[::-1])
def solution(equation:str):
    eq2=equation[::-1]
    li=re.findall(r'\d+',eq2)
    for i in range(len(li)):
        res=eq2.replace(li[i],li[i][::-1])
    return res

#思路:先倒序,然后用正则表达式匹配所有的数字,将数字再倒回来
def solution(equation: str) -> str:
    one_str = ''
    eq_list = []
    for i in equation + '*':
        if i not in ['*', '/', '+', '-']:
            one_str += i
        else:
            eq_list.append(one_str)
            eq_list.append(i)
            one_str = ''
    eq_list.pop()
    return ''.join(eq_list[::-1])

assert solution("100*b/y") == "y/b*100"
assert solution("a+b-c/d*30") == "30*d/c-b+a"
assert solution("a*b/c+50") == "50+c/b*a"
关闭