Home > Mobile >  I am trying to make a simple calculator without eval() and whole equations
I am trying to make a simple calculator without eval() and whole equations

Time:04-09

I am trying to make a simple calculator with an input of the whole equation, but the catch is that i can not use eval() or anything similar to it. I wrote something and is probably not the best solution but this is what i came up with. The problem is that if i enter "2 5" as an input the final output is an error saying that it can not int() "2 "

Here is the code:

print("Calculator 2.0")

while True:
    equation = input(": ")

    # Remove spaces
    calculate = equation.replace(" ", "")

    # Converting to list
    calculate = list(calculate)

    # Merging numbers next to one another
    i = 0
    startingIndex = -1
    numCounter = 1
    num = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
    while i < len(calculate):
        if calculate[i] in num:
            if startingIndex == -1:
                startingIndex = i
            numCounter  = 1
        else:
            calculate[startingIndex : numCounter] = [''.join(calculate[startingIndex : numCounter])]
            startingIndex = -1
            numCounter = 1
        i  = 1

    solved = False
    answer = 0
    
    while solved == False:
        # Check for multiplication and division
        i = 0
        while i < len(calculate):
            divideIndex = -1
            multiplyIndex = -1
            j = 0
            while j < len(calculate):
                if calculate[j] == "*":
                    multiplyIndex = j
                elif calculate[j] == "/":
                    divideIndex = j
                j  = 1
            
        
            # Solve the multiplication and division
            if multiplyIndex != -1:
                calculate[multiplyIndex] = str(int(calculate[multiplyIndex - 1]) * int(calculate[multiplyIndex   1]))
                del calculate[multiplyIndex - 1]
                del calculate[multiplyIndex   1]
            if divideIndex != -1:
                calculate[divideIndex] = str(int(calculate[divideIndex - 1] / int(calculate[divideIndex   1])))
                del calculate[divideIndex - 1]
                del calculate[divideIndex   1]

            i  = 1

        # Check for addition and subtraction
        i = 0
        while i < len(calculate):
            sumIndex = -1
            subtractIndex = -1
            j = 0
            while j < len(calculate):
                if calculate[j] == " ":
                    sumIndex = j
                elif calculate[j] == "-":
                    subtractIndex = j
                j  = 1
            
            # Solve the addition and subtraction
            if sumIndex != -1:
                calculate[sumIndex] = str(int(calculate[sumIndex - 1])   int(calculate[sumIndex   1]))
                del calculate[sumIndex - 1]
                del calculate[sumIndex   1]
            if subtractIndex != -1:
                calculate[subtractIndex] = str(int(calculate[subtractIndex - 1]) - int(calculate[subtractIndex   1]))
                del calculate[subtractIndex - 1]
                del calculate[subtractIndex   1]

            i  = 1

        answer = int(calculate[0])
        print(answer)
        solved = True

CodePudding user response:

Give this a shot:

def Numbers(var):
    return (
        var == "0"
        or var == "1"
        or var == "2"
        or var == "3"
        or var == "4"
        or var == "5"
        or var == "6"
        or var == "7"
        or var == "8"
        or var == "9"
    )


def Test4Num(varstr):
    n = 0
    var = ""
    try:
        while Numbers(varstr[n]):
            var  = varstr[n]
            n  = 1
    except:
        pass
    return (int(var), n)


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
    if string == "^":
        return num1**num2


def operator(operato):
    return (
        operato == " "
        or operato == "-"
        or operato == "*"
        or operato == "/"
        or operato == "^"
    )


def eval_math_expr(expr):
    negate = False
    expr = expr.replace(" ", "")

    while True:
        try:
            if expr[0] == "-":  # for negative numbers
                negate = True  # because here the numbers are string format
                expr = expr[1:]

            number1 = Test4Num(expr)[0]
            if negate == True:
                number1 = -number1
                negate = False
            end_number1 = Test4Num(expr)[1]
            expr = expr[end_number1:]

            if expr == "":
                return number1

            op = expr[0]
            expr = expr[1:]
            number2 = Test4Num(expr)[0]
            end_number2 = Test4Num(expr)[1]
            result = operation(op, number1, number2)
            number1 = result
            expr = str(number1)   expr[end_number2:]

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


if __name__ == "__main__":
    expr = input("Enter your expression:")
    print(expr   "=")
    print(eval_math_expr(expr))
  • Related