Question

In: Computer Science

push(self, value: object) -> None: This method adds a new element to the top of the...

push(self, value: object) -> None:

This method adds a new element to the top of the stack.

Output:

STACK: 0 elements. []

STACK: 5 elements. [1, 2, 3, 4, 5]

pop(self) -> object:

Output:

Exception: <class ' main .StackException'> 5

4

3

2

1

Exception: <class ' main .StackException'

top(self) -> object:

Output:

No elements in stack <class ' main .StackException'> STACK: 2 elements. [10, 20]

20

20

STACK: 2 elements. [10, 20]

#Code

from dynamic_array import *


class StackException(Exception):
"""
Custom exception to be used by Stack class
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
pass


class Stack:
def __init__(self):
"""
Init new stack based on Dynamic Array
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.da = DynamicArray()

def __str__(self) -> str:
"""
Return content of stack in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
out = "STACK: " + str(self.da.length()) + " elements. ["
out += ', '.join([str(self.da.get_at_index(_))
for _ in range(self.da.length())])
return out + ']'

def is_empty(self) -> bool:
"""
Return True is the stack is empty, False otherwise
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return self.da.is_empty()

def size(self) -> int:
"""
Return number of elements currently in the stack
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return self.da.length()

def push(self, value: object) -> None:
"""
TODO: Write this implementation
"""
pass

def pop(self) -> object:
"""
TODO: Write this implementation
"""
pass

def top(self) -> object:
"""
TODO: Write this implementation
"""
pass

# BASIC TESTING
if __name__ == "__main__":

print("\n# push example 1")
s = Stack()
print(s)
for value in [1, 2, 3, 4, 5]:
s.push(value)
print(s)

print("\n# pop example 1")
s = Stack()
try:
print(s.pop())
except Exception as e:
print("Exception:", type(e))

for value in [1, 2, 3, 4, 5]:
s.push(value)

for i in range(6):
try:
print(s.pop())
except Exception as e:
print("Exception:", type(e))

print("\n# top example 1")
s = Stack()
try:
s.top()
except Exception as e:
print("No elements in stack", type(e))
s.push(10)
s.push(20)
print(s)
print(s.top())
print(s.top())
print(s)

Solutions

Expert Solution

dynamic_array.py

import ctypes 
  
class DynamicArray(object): 
    def __init__(self): 
        self.n = 0 # Count actual elements (Default is 0) 
        self.capacity = 1 # Default Capacity 
        self.A = self.make_array(self.capacity) 
          
    def length(self): 
        return self.n 
      
    def get_at_index(self, k): 
        if not 0 <= k <self.n: 
            
            return IndexError('Index out of bounds !')  
          
        return self.A[k] # Retrieve from the array at index k 
          
    def append(self, ele): 
        if self.n == self.capacity: 
            self._resize(2 * self.capacity)  
          
        self.A[self.n] = ele 
        self.n += 1
  
          
    def pop(self):
        if self.n==0:
            print("Empty array")
            return
        else:
            item = self.get_at_index(self.n-1)
            self.n = self.n - 1
            return item
        
        
    
          
    def _resize(self, new_cap): 
        B = self.make_array(new_cap)
          
        for k in range(self.n):
            B[k] = self.A[k] 
              
        self.A = B 
        self.capacity = new_cap 
          
    def make_array(self, new_cap): 
        return (new_cap * ctypes.py_object)()

    def top(self):
        return self.get_at_index(self.n-1)

stack.py

from dynamic_array import *

class StackException(Exception):
    """
Custom exception to be used by Stack class
DO
"""
    pass

class Stack:
    da=DynamicArray()
    def __init_(self):
        """
Init new stack based on Dynamic Array
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
        self.da = DynamicArray()

    def __str__(self) -> str:
        """
Return content of stack in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
        out = "STACK: " + str(self.da.length()) + " elements. ["
        out += ', '.join([str(self.da.get_at_index(_))
        for _ in range(self.da.length())])
        return out + ']'

    def is_empty(self) -> bool:
        """
Return True is the stack is empty, False otherwise
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
        return self.da.is_empty()

    def size(self) -> int:
        """
Return number of elements currently in the stack
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
        return self.da.length()

    def push(self, value: object) -> None:
        """
TODO: Write this implementation
"""
        self.da.append(value)
        
    def pop(self) -> object:
        """
TODO: Write this implementation
"""
        x = self.da.pop()
        return x

    def top(self) -> object:
        """
TODO: Write this implementation
"""
        x = self.da.top()
        return x

# BASIC TESTING
if __name__ == "__main__":

    print("\n# push example 1")
    s = Stack()
    print(s)
    for value in [1, 2, 3, 4, 5]:
        s.push(value)
    print(s)

    print("\n# pop example 1")
    s = Stack()
    try:
        print(s.pop())
    except Exception as e:
        print("Exception:", type(e))

    for value in [1, 2, 3, 4, 5]:
        s.push(value)

    for i in range(6):
        try:
            print(s.pop())
        except Exception as e:
            print("Exception:", type(e))

    print("\n# top example 1")
    s = Stack()
    try:
        s.top()
    except Exception as e:
        print("No elements in stack", type(e))
    s.push(10)
    s.push(20)
    print(s)
    print(s.top())
    print(s.top())
    print(s)

Output


Related Solutions

python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value):...
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value): pass    def pop(self): return None    def peek(self): pass    def is_empty(self): pass def stack(self): pass    def exch(self): pass    def index(self): pass    def clear(self): pass    def dup(self): pass    def equal(self): pass    def depth(self): pass    stack = PostScript() def decode(command_list): for object in command_list: if object == '=': stack.equal() elif object == 'count': stack.depth() elif object ==...
Python linked lists ● Insert: this method takes a value as a parameter, and adds a...
Python linked lists ● Insert: this method takes a value as a parameter, and adds a node which contains the value to the end of the linked list ● Delete: this method deletes a node from the linked list. If an index is passed as a parameter, then the method should delete the node at this index. If no index is passed, then delete the first item in the list ● Find: this method takes a value as a parameter,...
Insert: this method takes a value as a parameter and adds a node which contains the...
Insert: this method takes a value as a parameter and adds a node which contains the value to the end of the linked list Delete: This method deletes a node from the linked list. If an index is passed as a parameter, then the method should delete the node at this index. If no index is passed, then delete the first item in the list Find: this method takes a value as a parameter, and returns the index of the...
1. A researcher is interested in comparing a new self-paced method of teaching statistics with the...
1. A researcher is interested in comparing a new self-paced method of teaching statistics with the traditional method of conventional classroom instruction. On a standardized test of knowledge of statistics, the mean score for the population of students receiving conventional classroom instruction is μ = 60. At the beginning of the semester, she administers a standardized test of knowledge of statistics to a random sample of 30 students in the self-paced group and finds the group mean is M =...
Cash Payback Period, Net Present Value Method, and Analysis McMorris Publications Inc. is considering two new...
Cash Payback Period, Net Present Value Method, and Analysis McMorris Publications Inc. is considering two new magazine products. The estimated net cash flows from each product are as follows: Year Canadian Cycling European Hiking 1 $155,000 $129,000 2 126,000 152,000 3 109,000 104,000 4 99,000 73,000 5 31,000 62,000 Total $520,000 $520,000 Present Value of $1 at Compound Interest Year 6% 10% 12% 15% 20% 1 0.943 0.909 0.893 0.870 0.833 2 0.890 0.826 0.797 0.756 0.694 3 0.840 0.751...
Cash Payback Period, Net Present Value Method, and Analysis McMorris Publications Inc. is considering two new...
Cash Payback Period, Net Present Value Method, and Analysis McMorris Publications Inc. is considering two new magazine products. The estimated net cash flows from each product are as follows: Year Canadian Cycling European Hiking 1 $120,000 $101,000 2 99,000 118,000 3 85,000 81,000 4 77,000 57,000 5 24,000 48,000 Total $405,000 $405,000 Present Value of $1 at Compound Interest Year 6% 10% 12% 15% 20% 1 0.943 0.909 0.893 0.870 0.833 2 0.890 0.826 0.797 0.756 0.694 3 0.840 0.751...
Fox Pty Ltd (Fox) is a listed company on ASX and is aiming to invest $500,000 into a new product line. The residual value of this investment at the end of 5 years would be $50,000, which is depreciated using Straight Line Method.
Fox Pty Ltd (Fox) is a listed company on ASX and is aiming to invest $500,000 into a new product line. The residual value of this investment at the end of 5 years would be $50,000, which is depreciated using Straight Line Method.This investment brings additional net operating income of $80,000 which would be increased by 7% each year till year 5. Also, for this investment, Fox is required to invest 3% of the new net operating income each year....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT