Question

In: Computer Science

"""stack.py implements stack with a list""" class Stack(object): def __init__(self): #creates an empty stack. O(1) self.top...

"""stack.py implements stack with a list"""

class Stack(object):
def __init__(self): #creates an empty stack. O(1)
self.top = -1 #the index of the top element of the stack. -1: empty stack
self.data = []

def push(self, item): # add item to the top of the stack. O(1)
self.top += 1
self.data.append(item)

def pop(self): # removes and returns the item at the top O(1)
self.top -=1
return self.data.pop()

def peek(self): # returns the item at the top O(1)
return self.data[len(self.data)-1]
def isEmpty(self): return self.top == -1 #return len(self.data)==0
def __len__(self): return self.top+1 #return len(self.data)

def __str__(self): return " ".join([str(x) for x in self.data])

#to do: add a main method to test the stack.

Solutions

Expert Solution

Below is the fully implemented code and added main method to test the stack

"""stack.py implements stack with a list"""

class Stack(object):
def __init__(self):
self.top = -1
self.data = []

def push(self, item):
self.top += 1
self.data.append(item)

def pop(self): # removes and returns the item at the top O(1)
self.top -=1
return self.data.pop()

def peek(self): # returns the item at the top O(1)
return self.data[len(self.data)-1]
  
def isEmpty(self):
return self.top == -1 #return len(self.data)==0
  
def __len__(self):
return self.top+1 #return len(self.data)

def __str__(self):
return " ".join([str(x) for x in self.data])

#to do: add a main method to test the stack.


s=Stack()

print(s.isEmpty()) # Return true if stack is empty and false if stack is not empty

s.push(4) # To push element 4 in stack

s.push(5) # To push element 5 in stack

print(s.peek()) # To see the top element in stack

s.push(6) # To push element 6 in stack

print(s.isEmpty()) # Return true if stack is empty and false if stack is not empty

s.push(9.2) # To push element 9.2 in stack

print(s.pop()) # To pop element of stack

print(s.pop()) # To pop element of stack

CONCEPT : I have just called the object of Stack class and make a object "s" with s i have c=made call to push() and and pop() and isEmpty() and peek() function hence these will return it's output once you execute the code.



Related Solutions

1) What is the argument in “class AddressBook(object):” 2) What is the roll of “def __init__(self):”?...
1) What is the argument in “class AddressBook(object):” 2) What is the roll of “def __init__(self):”? 3) What is the roll of “def __repr__ (self):”? 4) Please copy and run “Addressbook” Python program. Submit the code and the output 5) Discuss the two outputs’ differences (data type). 6) Please add 2 more people and report the output. Code: class AddressBook(object): def init_(self): self.people=[] def add_entry(self, new_entry): self.people.append(new_entry) class AddressEntry(object): def __init__(self, first_name=None, family_name= None, email_address= None, DOB= None): self.first_name =...
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)        &nb
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)               style = color                return    def plane(self,oil)              liquid = self.oil + self.truck(color) For the plane method, I am getting an error that the class does not define __add__ inside init so I cannot use the + operator. How do I go about this.             
How would I setup this dictionary for Python 3? class Student(object): def __init__(self, id, firstName, lastName,...
How would I setup this dictionary for Python 3? class Student(object): def __init__(self, id, firstName, lastName, courses = None): The “id”, “firstName” and “lastName” parameters are to be directly assigned to member variables (ie: self.id = id) The “courses” parameter is handled differently. If it is None, assign dict() to self.courses, otherwise assign courses directly to the member variable. Note: The “courses” dictionary contains key/value pairs where the key is a string that is the course number (like “course1”) and...
''' File: pyPatientLL.py Author: JD ''' class Node: #ADT        def __init__(self, p = None):             ...
''' File: pyPatientLL.py Author: JD ''' class Node: #ADT        def __init__(self, p = None):              self.name = ""              self.ss = self.age = int(0)              self.smoker = self.HBP = self.HFD = self.points = int(0)              self.link = None              #if list not empty              if p != None:                     p.link = self        ptrFront = ptrEnd = None choice = int(0) def menu():        print( "\n\tLL Health Clinic\n\n")        print( "1. New patient\n")        print( "2. View patient by...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a,...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a, b):        self.a = a        self.b = b    def add(self):        return self.a + self.b    def mul(self):        return self.a * self.b    def div(self):        return self.a / self.b    def sub(self):        return self.a - self.b def playQuiz():    print("0. Exit")    print("1. Add")    print("2. Subtraction")    print("3. Multiplication")    print("4. Division")...
Class AssignmentResult An object that represents the result of an assignment. __init__(self, id:int, assignment: Assignment, grade:...
Class AssignmentResult An object that represents the result of an assignment. __init__(self, id:int, assignment: Assignment, grade: float): """ This will contain the ID of the student, the assignment that the student worked on and the grade the student received on the assignment. :param id: The ID of the student that created this Assignment result :param assignment: The Assignment that the student worked on. :param grade: A number between 0-1 representing the numerical grade the student received """ id(self) -> int:...
Solve this Write a C++ class that implements a stack using a linked list. The type...
Solve this Write a C++ class that implements a stack using a linked list. The type of data contained in the stack should be double. The maximum size of the stack is 30. Implement the following methods: . · Constructor and destructor; // 5 pts · void push (double value); // pushes an element with the value into the stack. 5 pts. · double pop (); // pops an element from the stack and returns its value. 5 pts. ·...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class Stack{ public Stack(){ // use LinkedList class } public void push(int item){ // push item to stack } public int pop(){ // remove & return top item in Stack } public int peek(){ // return top item in Stack without removing it } public boolean isEmpty(){ // return true if the Stack is empty, otherwise false } public int getElementCount(){ // return current number...
The program (​ stack-ptr.c​ ) implements stack using a linked list, however, it contains a race...
The program (​ stack-ptr.c​ ) implements stack using a linked list, however, it contains a race condition and is not appropriate for a concurrent environment. Using Pthreads mutex locks, fix the race condition. For reference, see Section 7.3.1 of SGG book.(Section 7.3.1 is about mutex and semaphores it does explain how to implement I'm just having a hard time finding the race condition within the code) /* * Stack containing race conditions */ #include #include #include typedef int value_t; //...
Create the following java program with class list that outputs: //output List Empty List Empty List...
Create the following java program with class list that outputs: //output List Empty List Empty List Empty Item not found Item not found Item not found Original list Do or do not. There is no try. Sorted Original List Do There do is no not. or try. Front is Do Rear is try. Count is 8 Is There present? true Is Dog present? false List with junk junk Do or moremorejunk do not. There is no try. morejunk Count is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT