練習:求字符串中最長的表達式,並計算結果--python實現


1、判斷字符串長度、最長的表達式

"""
1、所有數字,計算長度不能超過long
2、如果有多個長度一樣,請返回第一個表達式結果
3、數學表達式必須要是最長的,合法的
4、操作符不能是連續的,如 +--+1是不合法的

"""

import re

s = input("請輸入字符串:")

#保留只有0-9 +-*字符
list1 = re.findall("[-+*0-9]+",s)
s0 = ""
for s1 in list1:
    lens = 0
    T = True
    for s2 in s1:#判斷是否有連續的運算符
        if s2 in ["-","+","*"]:
            lens+=1
            if lens > 1:
                print("不合法表達式:",s1)
                T = False
                break
        else:
            lens = 0
    if T:#求出最長的表達式
        if len(s0)<len(s1):
            s0 = s1

if s0 == "":
    A=0
else:
    if s0[0] == "*":
        s0 = s0[1:]
        if s0.find("*") == 1:
            print("暫時無法計算乘法:",s0)
        else:
            A = eval(s0)
    else:
        if s0.find("*") == 1:
            print("暫時無法計算乘法:", s0)
        else:
            A = eval(s0)
print(A)

  

2、計算器方法--百度的方法

# judgment a char is a operation or not
from pip._vendor.distlib.compat import raw_input


def is_operation(oper):
    if oper == '+' or oper == '-' or oper == '*' or oper == '/':
        return True
    else:
        return False


# split expression
def mixed_operation(exp):
    exp_list = list(exp)
    temp = ''
    behavor_list = []
    i = 0
    length = len(exp_list)
    for item in exp_list:
        if is_operation(item):
            behavor_list.append(int(temp))
            behavor_list.append(item)
            temp = ''
        else:
            temp += item

        if i == length - 1:
            behavor_list.append(int(temp))
            break
        i += 1

    return behavor_list


# cal a o b
def get_aob(a, o, b):
    if o == '+':
        return a + b
    elif o == '-':
        return a - b
    elif o == '*':
        return a * b
    elif o == '/':
        return a / b


# Calculation op1 and op2('*' and '/' or '+' and '-')
def cal_op1_op2(exp_list, op1, op2):
    if len(exp_list) == 1:
        return exp_list

    i = 0
    has_op = False
    for i in range(2, len(exp_list), 2):
        a = exp_list[i - 2]
        o = exp_list[i - 1]
        b = exp_list[i]
        if o == op1 or o == op2:
            has_op = True
            exp_list[i - 2] = get_aob(a, o, b)
            del exp_list[i]
            del exp_list[i - 1]
            break

    if has_op == False:
        return exp_list

    return cal_op1_op2(exp_list, op1, op2)


# cal exp
def cal_exp(exp_list):
    exp_list = cal_op1_op2(exp_list, '*', '/')
    exp_list = cal_op1_op2(exp_list, '+', '-')

    return exp_list[0]

# while True:
expre = input('Enter your expression(0 to end):')
    # if expre == '0':
    #     break

result = mixed_operation(expre)
print('list result = ',result)
print(cal_exp(result))

#print ('END')

  

遺留問題解決方法:

計算器方法里沒有判斷表達式首字符是運算符情況,加個判斷,再使用上計算器方法結合,就能計算合法的最長表達式結果了。

 

2021-1-2,筆記


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM