2 Replies - 9397 Views - Last Post: 11 December 2012 - 05:26 AM Rate Topic: -----

#1 ann_sh   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-December 12

Stacks in python (Postfix evaluation)

Posted 10 December 2012 - 07:46 PM

Hey everyone!

I need some help to complete this code i am doing for my programming class. I a working with stacks and need to create a program that evaluates postfix notations. I have input 'expressions.txt' file that has all the postfix notations i need to evaluate. My program evaluates 6 out of 10 notations, i need help to do the rest 4.

Attached along is the text file that contains postfix notations. I am attaching Stacks.py and ListNode.py files with changed file format to .txt so that i can upload them.

I am also pasting my driver.py program here. Any input is highly appreciated. Thanks in advance.

from Stack import *

def postFix(expression):
    myStack= Stack()
    tokenList= expression.split()

    for token in tokenList:
        if token.isdigit():
            myStack.push(int(token))
            
        elif token == '+':
            if not myStack.is_empty():
                x = myStack.pop()
            else:
                print("\nERROR: ", expression, "is an invalid postfix expression.")
                break
            if not myStack.is_empty():
                y = myStack.pop()
            else:
                print("\nERROR: ", expression, "is an invalid postfix expression.")
                break
            summ = x + y
            myStack.push(summ)
        elif token == '-':
            if not myStack.is_empty():
                x = myStack.pop()
            else:
                print("\nERROR: ", expression, "is an invalid postfix expression.")
                break
            if not myStack.is_empty():
                y = myStack.pop()
            else:
                print("\nERROR: ", expression, "is an invalid postfix expression.")
                break
            subs = y - x
            myStack.push(subs)
        elif token == '*':
            if not myStack.is_empty():
                x = myStack.pop()
            else:
                print("\nERROR: ", expression, "is an invalid postfix expression.")
                break
            if not myStack.is_empty():
                y = myStack.pop()
            else:
                print("\nERROR: ", expression, "is an invalid postfix expression.")
                break
            prod = x * y
            myStack.push(prod)
        elif token == '/':
            if not myStack.is_empty():
                x = myStack.pop()
            else:
                print("\nERROR: ", expression, "is an invalid postfix expression.")
                break
            if not myStack.is_empty():
                y = myStack.pop()
            else:
                print("\nERROR: ", expression, "is an invalid postfix expression.")
                break
            divi = y / x
            myStack.push(divi)
            
        else:
            print("\nERROR: ", expression, "is an invalid postfix expression.")
    return myStack.pop()
    

#Main program
FileName = input("Enter the name of the file containing postfix expressions: ")
user = open(FileName , 'r')
for each in user:
  line= each.strip()
  print ("\n","Expression: ",line, "\n", "Answer: ", postFix(line))
user.close()

Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: Stacks in python (Postfix evaluation)

#2 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 12350
  • View blog
  • Posts: 20,984
  • Joined: 19-March 11

Re: Stacks in python (Postfix evaluation)

Posted 10 December 2012 - 08:39 PM

Could you maybe point out where you're getting errors? It's more likely that someone's going to spot your problem if you tell us exactly what the problem is.

Just to make life a little easier, here are the source and data files:

class ListNode(object):
    def __init__(self, item = None, link = None):
        """creates a ListNode with the specified        
        data value and link
        post:  creates a ListNode with the specified 
        data value and link"""

        self.item = item
        self.link = link

    def get_link(self):
        return self.link
    
    def get_item(self):
        return self.item
    
    def set_item(self, newValue):
        self.item = newValue
        
    def set_link(self, newLink):
        self.link = newLink
            
    def __repr__(self):
        return str(self.item)

    def __str__(self):
        return str(self.item)




from ListNode import *

class Stack:
    #Constructor may create an empty list or one with an item sent by client
    def __init__(self, item = None):
        if item == None:
            self.top = None
        else:
            self.top = ListNode(item)
            
    #Inserts an item at the beginning of the list
    def push(self, item):
        self.top = ListNode(item, self.top)

    #Deletes the first item in the linked list
    def pop(self):
        if self.is_empty():
            raise Exception ("ERROR:  Trying to pop from an empty stack")
        x = self.top.get_item()
        self.top = self.top.get_link()
        return x

    #Checks to see if the stack is empty
    def is_empty(self):
        if self.top == None:
            return True
        return False

    #Checks to see if the stack is full (not going to happen with this representation)
    def is_full(self):
        return False

    def destroy(self):
        self.top = None


Expressions.txt:


8 5 *
20 5 /
3 8 6 + *
3 4 + 9 - 12 +
9 3 2 1 + + /
3 + 4
* 3 4 5 + *
4 9 1 3 + -
h 3 +

This post has been edited by jon.kiparsky: 10 December 2012 - 08:48 PM

Was This Post Helpful? 0
  • +
  • -

#3 Nallo   User is offline

  • D.I.C Regular
  • member icon

Reputation: 166
  • View blog
  • Posts: 258
  • Joined: 19-July 09

Re: Stacks in python (Postfix evaluation)

Posted 11 December 2012 - 05:26 AM

Problem is:
I. Your postfix function always returns myStack.pop() whether there was an error or not.
II. Before return myStack.pop() check that there was exactly one element on the stack (otherwise 4 9 1 3 + - would not be detected as invalid)

Instead of printing an error from the function you could return None. And then let the main program do the check whether None or a valid result gets returned. I.e:
In the postfix function
#replace this lines
print("\nERROR: ", exp<b></b>ression, "is an invalid postfix exp<b></b>ression.")
break

#with
return None


main:
...
for each in user:
  line= each.strip()
  result = postFix(line)
  if result is None:
    print("\nERROR: ...")
  else:
    print ("\n","Exp<b></b>ression: ",line, "\n", "Answer: ", postFix(line))
...


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1