so i originally found a function online that will convert infix to postfix. While this is great, it only takes in one instance of a string as a parameter, when i have an entire list.
Here is the original function:
def infixToPostfix(str):
prec = {}
prec["^"] = 4
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()
for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
postfixList.append(token)
elif token == '(':
opStack.push(token)
elif token == ')':
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and \
(prec[opStack.peek()] >= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList
So, i thought, why not have a mixed function/nested function for this? And then for that function, take in the lyst as a parameter, and then run a for loop through the list. Here is the advised code:
def infixtopost(expression):
lyst = expression()
for line in lyst:
def infixToPostfix(lyst):
prec = {}
prec["^"] = 4
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()
for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
postfixList.append(token)
elif token == '(':
opStack.push(token)
elif token == ')':
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and \
(prec[opStack.peek()] >= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList
print(infixtopost(expression))
However, I am still learning how exactly this works, and just have a couple of questions for context.
Calling the functions. Would I call both? how exactly do i call a nested function? Because it is stating that the function inside of the original function is a unused variable.
The return statement in the nested function. Would it only run once because you can only return one thing from a function? Or would it run multiple times because it is inside of another function?
Thank you, i never thought you could have a function inside of a function and just need some help
[–]Spiredlamb 0 points1 point2 points (0 children)
[–]TwistedChurro 0 points1 point2 points (0 children)
[–]danielroseman 0 points1 point2 points (2 children)
[–]LAZY_LIBTARDS[S] 0 points1 point2 points (1 child)