Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculate stack value's
#1
Hi everyone im new to python and still trying to get a hang for it and ive ran into a problem when creating my basic stack program and cant figure out where to go next was hoping if anyone could guide me the right way :)
here is the code:
class stack():
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def get_stack(self):
        return self.items

    def is_empty(self):
        return self.items == []

    def is_full(self):
        return self.items == [1]

    def size(self):
        return len(self,items)


s = stack()
print("ar stack tuscias?")
print(s.is_empty())
print("ar stack pilnas?")
print(s.is_full())
s.push(9)
s.push('+')
s.push(5)
s.push('+')
s.push(8)
s.push('+')
s.push(7)

s.push('+')
s.push(3)
print(s.size())
print(s.get_stack())
This program works on it self just fine the problem i have is how do i take value of "s.push(x)" and add it or multiply or w/e and get an answer in this example how do i make him 9+5+8+7+3 whitout just writing print 9+5 was hopping to get answer with define so if numbers or symbol changes it would react acording to it.
here of what i was thinking of but gotten stuck on
       for symbol in self:
            if symbol in "0123456789":
                s.append(int(symbol))
   
            if symbol == "+":
                plus = s.pop() + s.pop()
            elif symbol == "-":
                plus = s.pop() - s.pop()
            elif symbol == "*":
                plus = s.pop() * s.pop()
            elif symbol == "/":
                plus = s.pop() / s.pop()
its one of those moments where i think im close but cant figure it out
Reply
#2
I'm not sure if that's what you're looking for but there's eval(str) function to which you can supply mathematical expression in the form of string, for example:
eval("5+5")
Output:
10
Reply
#3
well this would be a short term solution that would only work with a current program but if i ware to change numbers i dont think answer would change automaticly what im trying to do is find a way how to define a function that it would calculate all of my s.push commands
Reply
#4
It takes string as input and strings are easy to modify/organise. You can do this:
eval(str(s.pop()) + symbol + str(s.pop()))
and it automatically replaces this part that you posted:
if symbol == "+":
         plus = s.pop() + s.pop()
     elif symbol == "-":
         plus = s.pop() - s.pop()
     elif symbol == "*":
         plus = s.pop() * s.pop()
     elif symbol == "/":
         plus = s.pop() / s.pop()
You can also have a list of symbols and format them all into 1 eval function.
Reply
#5
would this then mean that i take poped element then try to add to with a symbol who is for example + and add it with the other poped element and get result ? and where exactly should i write this command ?
meanwhile i was trying to upgrade my own:


class stack():
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def get_stack(self):
        return self.items

    def is_empty(self):
        return self.items == []

    def is_full(self):
        return self.items == [1]

    def size(self):
        return len(self.items)



    def eval(self):
        s = stack()
        for symbol in self:
            if symbol in "0123456789":
                s.append(int(symbol))

            plus = None
            elif not s.is_empty():
            if symbol == "+":
                plus = s.push() + s.push()
            elif symbol == "-":
                plus = s.push() - s.push()
            elif symbol == "*":
                plus = s.push() * s.push()
            elif symbol == "/":
                plus = s.push() / s.push()

        if plus is not None:
            s.append(plus)
        else:
            raise Exception("unknown value %s" % symbol)

    return s.pop()


s = stack()
print("Is stack empty?")
print(s.is_empty())
print("Is stack Full?")
print(s.is_full())
s.push(9)
s.push('+')
s.push(5)
s.push('+')
s.push(8)
s.push('+')
s.push(7)

s.push('+')
s.push(3)
print(s.size())
print(s.get_stack())
print(s.eval())

s.pop()
s.pop()
print(s.get_stack())
but ran into a problem where it does not recognize this comand and i can seem to figure out why:
Error:
elif not s.is_empty(): ^ SyntaxError: invalid syntax
Reply
#6
I was going to try and explain how you could go about doing it and point you in a direction.
Explaining would be hard work, so see the following code and ask questions about any of it that doesn't makes sense.

Using the operator module create a symbol dict.
import operator

symbol_dict = {'+': operator.add, '-': operator.sub,
               '*': operator.mul, '/': operator.truediv}
Add the following method that makes use of the symbol dict
    def calculate_stack(self):
        if self.is_empty():
            return 0
        items = self.get_stack()
        total = items[0]
        symbol = None

        for item in items[1:]:
            if symbol:
                total = symbol_dict[symbol](total, item)
                symbol = None
            elif item in ("+", "-", "*", "/"):
                symbol = item

        return total
Full code
import operator

symbol_dict = {'+': operator.add, '-': operator.sub,
               '*': operator.mul, '/': operator.truediv}


class stack():
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def get_stack(self):
        return self.items

    def is_empty(self):
        return self.items == []

    def is_full(self):
        return self.items == [1]

    def size(self):
        return len(self.items)

    def calculate_stack(self):
        if self.is_empty():
            return 0
        items = self.get_stack()
        total = items[0]
        symbol = None

        for item in items[1:]:
            if symbol:
                total = symbol_dict[symbol](total, item)
                symbol = None
            elif item in ("+", "-", "*", "/"):
                symbol = item

        return total


s = stack()
print("ar stack tuscias?")
print(s.is_empty())
print("ar stack pilnas?")
print(s.is_full())
s.push(9)
s.push('+')
s.push(5)
s.push('+')
s.push(8)
s.push('+')
s.push(7)
s.push('+')
s.push(3)
print(s.size())
print(s.get_stack())


print(s.calculate_stack())
s2 = stack()
s2.push(2)
s2.push('*')
s2.push(4)
s2.push('-')
s2.push(1)
print(s2.calculate_stack())
Output:
ar stack tuscias? True ar stack pilnas? False 9 [9, '+', 5, '+', 8, '+', 7, '+', 3] 32 7
Reply
#7
oh wow i had quite a work ahead of me was not expecting this much
there is a few things that are unclear like what does import operator exactly do but i feel like i could just google these things instead of wasting your time
and what does the 0 mean in "total = items[0]"
and in this line for item in items[1:] what does [1:] do
other then that it seems somewhat clear just need to analyze it more
also one last question i remember there being a help meniu that brings litle pop up when i highlight a command and press something on jetbrains pycharm
Reply
#8

  1. what does import operator exactly do
    https://docs.python.org/3/library/operat...e-operator Wrote:The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. Many function names are those used for special methods, without the double underscores. For backward compatibility, many of these have a variant with the double underscores kept. The variants without the double underscores are preferred for clarity.

    The functions fall into categories that perform object comparisons, logical operations, mathematical operations and sequence operations.

    The object comparison functions are useful for all objects, and are named after the rich comparison operators they support:

  2. what does the 0 mean in "total = items[0]"
    When you use [] on a list you can get an item by its index, the list is zero index based so this gives the first item contained in the list.

  3. in this line for item in items[1:] what does [1:] do
    this is called slicing the list, it gives parts of the list [from:to] so im getting from index 1 and as i've given no to value it gives the rest of the list.
mylist = [0, 1, 2, 3, 4, 5]
print(mylist[0])
print(mylist[1:])
Output:
0 [1, 2, 3, 4, 5]
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020