-1

Using this stack:

class myStack:
    def __init__(self):
        self.container = []
    def __repr__(self):
        return "Stack({})".format(self.container)
    def push(self,item):
        self.container.append(item)
    def __iter__(self):
        return reversed(self.container)
    def pop(self):
        return self.container.pop()
    def len(self):
        return len(self.container)

Could you write a client function called parenthesesMatch? Given a string containing only the characters for parentheses, braces or curly braces, i.e., the characters in ’([{}])’, returns True if the parentheses, brackets and braces match and False otherwise.

This is my algorithm: 1. Create an empty stack. 2. Iterate over the characters in the given string: a. If the character is one of opening marks(,[,{ push it on the stack. b. If the character is one of the closing marks ),],} and the stack is empty, then there were not enough preceding opening marks, so return False. c. If the character is a closing mark and the stack is not empty, pop an (opening) mark from the stack. If they are not of the same type, ie., ( and ) or [ and ] or { and }, return False, if they are of the same type, move on to the next char. 3. Once the iteration is finished, you know that the parentheses match if and only if the stack is empty.

  • And what is your question exactly? – Thierry Lathuille Apr 10 '18 at 15:46
  • 1
    you are not returning the result in the `len()` method, so you need to add `return` before `len(self.container)`. And you should rename the method to `__len__()`, so `len(stack_instance)` works as expected. – Sven Marnach Apr 10 '18 at 15:48
  • You forgot the `return` statement in `len()`, that's why is does not work. Also this seems like a job for [collections.deque](https://docs.python.org/2/library/collections.html#collections.deque) – etene Apr 10 '18 at 15:48
  • Right now my __init__ only constructs an empty stack. How could I add an attribute for it to be initialized with a list? Like if s = Stack(['apple', 'pear', 'kiwi']), it would start it up –  Apr 10 '18 at 15:49
  • You should also rename `iter()` to `__iter__()` and change `reverse` to `reversed`. – Sven Marnach Apr 10 '18 at 15:50
  • Possible duplicate of [Implementing stack in python by using lists as stacks](https://stackoverflow.com/questions/5695487/implementing-stack-in-python-by-using-lists-as-stacks) – handle Apr 10 '18 at 15:52
  • 1
    Instead of completely rewriting, please just add additional information or questions. – handle Apr 10 '18 at 16:01
  • Please do NOT change the question when you edit, because it renders the answers non-sequitur, and different answers at different times will answer different questions. – Jeff Learman Apr 10 '18 at 16:04
  • Wow, now it looks like you've just posted your assignment... – handle Apr 10 '18 at 16:07
  • OK, now you've completely changed the question into one that is not appropriate for this site. We don't permit "please write code for me" posts. – Jeff Learman Apr 10 '18 at 16:09

3 Answers3

1

See the Python tutorial on Using Lists as Stacks and the documentation on Classes.

Just two slight modifications, and it seems to work:

class myStack:
    def __init__(self):
        self.container = []
    def __repr__(self):
        return "Stack({})".format(self.container)
    def push(self,item):
        self.container.append(item)
    def iter(self):
        return self.container.reverse()  # !
    def pop(self):
        return self.container.pop()
    def len(self):
        return len(self.container)  # !

s = myStack()
print(s)

s.push("something")
print(s)
s.push("something completely different")
print(s)

print(s.len())
s.iter()
print(s)

s.pop()
print(s)
s.pop()
print(s)

s.pop()
print(s)

produces

Stack([])
Stack(['something'])
Stack(['something', 'something completely different'])
2
Stack(['something completely different', 'something'])
Stack(['something completely different'])
Stack([])
Traceback (most recent call last):
  File "t.py", line 37, in <module>
    s.pop()
  File "t.py", line 16, in pop
    return self.container.pop()
IndexError: pop from empty list

You could prevent this last error by first checking if the pop() can be done.

See Emulating container types regarding all the "special" class methods. So to access an element by index just like with a list, e.g s[1], you might add

def __getitem__(self,key):
        return self.container[key]

and get e.g. something completely different.

handle
  • 5,859
  • 3
  • 54
  • 82
0

You were almost there, here is a slight suggestion your init function.

    class myStack:

        def __init__(self,init=None):
          if init is None:
            init=[]
          self.container = init
        def __repr__(self):
          return "Stack({})".format(self.container)
        def push(self,item):
          self.container.append(item)
        def iter(self):
          return reverse(self.container)
        def pop(self):
          return self.container.pop()
        def len(self):
          return len(self.container)

also if you want that instead of using ".len()" to find number of values in your stack, you could just write "len(a)"(override) where a is your class object. you can change your len code to.

def __len__(self):
  return len(self.container)

in your class

Shivam Chawla
  • 390
  • 5
  • 17
0

To initialize with a non-empty stack (the main question your original post asked), provide an optional argument to the __init__ function:

def __init__(self, items=None):
    if items == None:
        items = []
    items.reverse() # (you might or might not want this)
    self.container = items

To override len:

def __len__(self):
    return len(self.container)
Jeff Learman
  • 2,914
  • 1
  • 22
  • 31