Question: python programming Complete and test the linked and array implementations of the stack collection type discussed in this chapter. Verify that exceptions are raised when

python programming

Complete and test the linked and array implementations of the stack collection type discussed in this chapter. Verify that exceptions are raised when preconditions are violated and that the array-based implementation adds or removes storage as needed.

Changes should be made in both the linkedstack.py and arraystack.py files. Run file teststack.py to test your stack implementations.

code linkedstack.py:

"""

File: linkedstack.py

"""

from node import Node

from abstractstack import AbstractStack

class LinkedStack(AbstractStack):

"""A link-based stack implementation."""

# Constructor

def __init__(self, sourceCollection = None):

"""Sets the initial state of self, which includes the

contents of sourceCollection, if it's present."""

# Accessor methods

def __iter__(self):

"""Supports iteration over a view of self.

Visits items from bottom to top of stack."""

def visitNodes(node):

"""Adds items to tempList from tail to head."""

def peek(self):

"""

Returns the item at the top of the stack.

Precondition: the stack is not empty.

Raises: KeyError if the stack is empty."""

if self.isEmpty():

# Mutator methods

def clear(self):

"""Makes self become empty."""

def push(self, item):

"""Adds item to the top of the stack."""

def pop(self):

"""

Removes and returns the item at the top of the stack.

Precondition: the stack is not empty.

Raises: KeyError if the stack is empty.

Postcondition: the top item is removed from the stack."""

=================================================================

node code :

"""

File: node.py

Author: Ken Lambert

"""

class Node(object):

"""Represents a singly linked node."""

def __init__(self, data, next = None):

self.data = data

self.next = next

==========================================

"""

File: abstractstack.py

Author: Ken Lambert

"""

from abstractcollection import AbstractCollection

class AbstractStack(AbstractCollection):

"""An abstract stack implementation."""

# Constructor

def __init__(self, sourceCollection = None):

"""Sets the initial state of self, which includes the

contents of sourceCollection, if it's present."""

AbstractCollection.__init__(self, sourceCollection)

# Mutator methods

def add(self, item):

"""Adds item to self."""

self.push(item)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!