我试图制作一个不使用eval()的计算器,并将整个方程作为字符串.此外,我不能使用任何库、模块等.我已经设法制作了一些东西,但我不知道如何先做乘法和除法,然后再做其余的.

4 + 4 * 4 = 20

4 + 4 * 4 + 4 = 4

编辑:所以我找到了问题所在,但它仍然不能正常工作.问题是代码甚至没有到达找到"*"的部分.我会用箭在它够不着的地方做标记.

以下是代码,请提前感谢:

print("Calculator")

# All the numbers
def numbers(num):
    return(
        num == "0"
        or num == "1"
        or num == "2"
        or num == "3"
        or num == "4"
        or num == "5"
        or num == "6"
        or num == "7"
        or num == "8"
        or num == "9"
    )

# All the operators
def operator(oprt):
    return(
        oprt == "+"
        or oprt == "-"
        or oprt == "*"
        or oprt == "/"
    )

# Removes all the spaces
def remove_spaces(string):
    string = string.replace(" ", "")
    return string

# Does the math between two numbers
def operation(string, num1, num2):
    if string == "+":
        return num1 + num2
    if string == "-":
        return num1 - num2
    if string == "*":
        return num1 * num2
    if string == "/":
        return num1 / num2

# Tests how long the number is
def test_number(numstr):
    n = 0
    num = ""

    try:
        while numbers(numstr[n]):
            num += numstr[n]
            n += 1
    except:
        pass

    return(int(num), n)

# Solves the equation
def eval_equation(eq):
    negative = False

    # Removes the spaces
    eq = remove_spaces(eq)

    while True:
        try:
            # Checks if the first number is negative
            if eq[0] == "-":
                negative = True
                eq = eq[1:]

            # Solves the multiplication first
            i = 0
            eqTemp = ""
            if "*" in eq:
                try:
                    while i < len(eq):
                        if eq[i] == "+" or eq[i] == "-" or eq[i] == "/":
                            eqTemp = eqTemp + eq[:i + 1]
                            print(f"eqTemp = {eqTemp}")
                            eq = eq[i + 1:]
                            print(f"eq = {eq}")
                        elif eq[i] == "*": # <-------this is the problem----
                            break
                            print(f"eqTemp = {eqTemp}")
                            print(f"eq = {eq}")
                            
                            
                        i += 1
                except:
                    i = 0

            # Checks the lenght of the number
            number1 = test_number(eq)[0]

            # Returns the "-" in the negative number
            if negative == True:
                number1 = -number1
                negative = False

            # Removes the first number from the string to continue with the next
            endNumber1 = test_number(eq)[1]
            eq = eq[endNumber1:]

            # Checks for any more numbers
            if eq == "":
                return number1

            # This is the operator sign
            op = eq[0]
            eq = eq[1:]

            # Repeats the same process with the other number
            number2 = test_number(eq)[0]
            endNumber2 = test_number(eq)[1]

            result = operation(op, number1, number2)
            
            # Takes the result and passes it as to the first number along with the rest of the equation
            number1 = result
            eq = str(number1) + eq[endNumber2:]

            eq = eqTemp + eq

        except Exception as error:
            print(error)
            break
    
    return number1
    

# Main function
if __name__ == "__main__":
    while True:
        equation = input(": ")
        print(eval_equation(equation))

推荐答案

所以我把它修好了.我不知道怎么...但我修好了.我现在只需要弄清楚如何向方程中添加变量:).以下是代码,感谢所有提出 idea 的人:

print("Calculator")

# All the numbers
def numbers(num):
    return num in {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}

# All the operators
def operator(oprt):
    return oprt in {"+", "-", "*", "/"}

# Removes all the spaces
def remove_spaces(string):
    string = string.replace(" ", "")
    return string

# Does the math between two numbers
def operation(string, num1, num2):
    if string == "+":
        return num1 + num2
    if string == "-":
        return num1 - num2
    if string == "*":
        return num1 * num2
    if string == "/":
        return int(num1 / num2)

# Tests how long the number is
def test_number(numstr):
    n = 0
    num = ""

    try:
        while numbers(numstr[n]):
            num += numstr[n]
            n += 1
    except:
        pass

    return(int(num), n)

# Solves the equation
def eval_equation(eq):
    negative = False

    # Removes the spaces
    eq = remove_spaces(eq)

    while True:
        try:
            # Checks if the first number is negative
            if eq[0] == "-":
                negative = True
                eq = eq[1:]

            # Solves the multiplication first
            i = 0
            eqTemp = ""
            if "*" in eq:
                try:
                    while i < len(eq):
                        if eq[i] in {"+", "-", "/"}:
                            eqTemp = eqTemp + eq[:i + 1]
                            #print(f"eqTemp = {eqTemp}")
                            eq = eq[i + 1:]
                            #print(f"eq = {eq}")
                            pass
                        if numbers(eq[i]) == True:
                            pass
                        if eq[i] == "*":
                            break                            
                            
                        i += 1
                except IndexError:
                    i = 0

            # Solves the division first
            i = 0
            eqTempDiv = ""
            if "/" in eq:
                try:
                    while i < len(eq):
                        if eq[i] in {"+", "-", "*"}:
                            eqTempDiv = eqTempDiv + eq[:i + 1]
                            #print(f"eqTemp = {eqTemp}")
                            eq = eq[i + 1:]
                            #print(f"eq = {eq}")
                            pass
                        if numbers(eq[i]) == True:
                            pass
                        if eq[i] == "/":
                            break                            
                            
                        i += 1
                except IndexError:
                    i = 0

            # Checks the lenght of the number
            number1 = test_number(eq)[0]

            # Returns the "-" in the negative number
            if negative == True:
                number1 = -number1
                negative = False

            # Removes the first number from the string to continue with the next
            endNumber1 = test_number(eq)[1]
            eq = eq[endNumber1:]

            # Checks for any more numbers
            if eqTempDiv == "":
                if eqTemp == "":
                    if eq == "":
                        return number1

            # This is the operator sign
            op = eq[0]
            eq = eq[1:]

            # Repeats the same process with the other number
            number2 = test_number(eq)[0]
            endNumber2 = test_number(eq)[1]

            result = operation(op, number1, number2)
            
            # Takes the result and passes it as to the first number along with the rest of the equation
            number1 = result
            eq = str(number1) + eq[endNumber2:]

            eq = eqTemp + eqTempDiv + eq
            #print(f"eqTemp final = {eqTemp}")
            #print(f"eq final = {eq}")

        except Exception as error:
            print(error)
            break
    
    return number1
    

# Main function
if __name__ == "__main__":
    while True:
        equation = input(": ")
        print(eval_equation(equation))

Python相关问答推荐

try 与gemini-pro进行多轮聊天时出错

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

如何标记Spacy中不包含特定符号的单词?

未删除映射表的行

如何从.cgi网站刮一张表到rame?

如何更改分组条形图中条形图的 colored颜色 ?

如何获得每个组的时间戳差异?

多指标不同顺序串联大Pandas 模型

如何在TensorFlow中分类多个类

OpenGL仅渲染第二个三角形,第一个三角形不可见

为什么我的sundaram筛这么低效

我对这个简单的异步者的例子有什么错误的理解吗?

一维不匹配两个数组上的广义ufunc

无法在盐流道中获得柱子

递归链表反转与打印语句挂起

时间戳上的SOAP头签名无效

如何通过函数的强式路径动态导入函数?

使用元组扩展字典的产品挑战

搜索结果未显示.我的URL选项卡显示:http://127.0.0.1:8000/search?";,而不是这个:";http://127.0.0.1:8000/search?q=name";