Turning infix notation to prefix notation has problems in formatting (Python)

37 Views Asked by At

I'm trying to create a program that turns infix notation to prefix notation, regardless of what kind of number the user inputs(like it could be a variable like A B or am integer like 3 34 23) here's the code:

def isDigit(To_check: str):
    ignore = ['-', '+', '*', '/', '^', '(', ')', '%']
    if not To_check in ignore: return True
    else: return False
def to_prefix(infix_expression: str):
    temp = list(infix_expression)
    output = []
    operator = []
    elements = []
    priority = {'(':0, ')':0, '+':1, '-':1, '/':2, '*':2, '^':3}
    temp2 = ""
    for i in range(len(temp)):
        reachedOp = False
        for op, val in priority.items():
            if temp[i] != op: continue
            else:
                reachedOp = True
                break
        if not reachedOp: temp2 += temp[i]
        else:
            if temp2 == '': continue
            elements.append(temp2)
            temp2 = ""
    if temp2 != '':
        elements.append(temp2)
    del temp, temp2
    for c in infix_expression[::-1]:
        if c == ')': operator.append(c)
        elif c == '(':
            while operator[-1] != ')': output.append(operator.pop())
            operator.pop()
        elif c == '^' or c == '/' or c == '*' or c == '+' or c == '-':
            if len(operator)>0:
                while priority[operator[-1]] > priority[c]:
                    output.append(operator.pop())
                    if len(operator) == 0: break
            operator.append(c)
        else: output.append(c)
    if len(operator) > 0:
        while len(operator) != 0: output.append(operator.pop())
    result = ""
    temp = ""
    temp2 = []
    reachedPrefix = False
    for e in output[::-1]:
        if e == ' ': continue
        temp+=e
    for w in temp:
        if not reachedPrefix and isDigit(w):
            temp2.append(' ')
            reachedPrefix = True
        temp2.append(w)
    temp3 = ""
    i = 0
    while i != len(temp2):
        temp3 += temp2[i]
        if temp2[i] == ' ' or temp2[i] == '' or not isDigit(temp2[i]): temp3 = ""
        if temp3 in elements:
            temp2.insert(i+1, ' ')
            temp3 = ""
        i+=1
    del temp, temp3
    reachedPrefix = False
    j = 0
    while j != len(temp2):
        if not reachedPrefix and isDigit(temp2[j]):
            reachedPrefix = True
            j+=1
            continue
        result+=temp2[j]
        j+=1
    del temp2
    return result
def add_spaces(string: str):
    space = ' '
    temp = string.split(" ")
    string = ""
    for e in temp:
        if e != '': string+=e
    del temp
    Lstring = list(string)
    for i in range(len(Lstring)*2):
        if i%2==0: Lstring.insert(i, space)
    string = ""
    for e in Lstring: string+=e
    return string[1:]

print(to_prefix(input()))

The problem being, our teacher is so tough and gave us an example and says it should output exactly like this:

#Input: 1-2-33
#output: --1 2 33

Now, I finally managed to do it but the problem is if my teacher thinks to try other numbers and maybe even variables, in some cases its formatting won't look like how he wants. for example, this is what I put in and what I get:

#input: (9-81)*(2+21)
#output: *-9 81 +2 2 1
--> expected: *-9 81 + 2 21

and this one:

#input: (A-8)*(34+21)
#output: *-A 8 +34 21
--> expected: *-A 8 + 34 21

I've been on this for 2 days straight and haven't sleep, so tired, I just want to get done with this, made many changes but never worked the way expected, What changes should be made in the code to get these exact results?

Thanks a lot in advanced <3

1

There are 1 best solutions below

1
Jitendra Singh Pancholi Jitend On

If we are converting the expression from infix to prefix, we need first to reverse the expression. To obtain the prefix expression, we have created a table that consists of three columns, i.e., input expression, stack, and prefix expression. When we encounter any symbol, we simply add it into the prefix expression. And..I.am.explained my answer.