Question

In: Computer Science

python Write a Loop class. The contents of a loop object are represented internally as a...

python

Write a Loop class. The contents of a loop object are represented internally as a simple python list with the following additional instance variables:

loop - a python list containing the elements of the loop list

head - which stores the index of the first element of the loop list

current - which stores the index of the last element of the loop list

size - which stores how many actual elements are in the loop

max - which stores the max number of elements that can be in a loop

Note that current and head will be the same when the list is empty, and when the list contains a single element.

And methods:

__init__(self, max) - which constructs an empty loop object;

__str__(self) - which returns a string representing the loop object as described below;

add(element) - which adds the element to the end of the loop (i.e. at the position of current + 1)

empty() - which says whether there are any elements in the loop;

count() - which says how many elements currently are in the loop;

delete() - which returns the first item from the loop (i.e. at the position of head) and removes it from the loop;

max() - returns the max number of elements allowed in the loop.

__init__ initializes the empty locations in the loop list to None. Assume that max is always greater than the number of elements to be in the loop at any one time. When an element is being added to an empty loop, it always goes into the first location (index 0) in the loop list and head and current are reset to 0.

If an attempt is made to delete() from an empty loop then delete()  returns None. When an element is deleted from the loop its value is changed to None. Remember, your code needs to properly maintain the correct values of loop, head, current and size.

__str__ formats the loop object data as follows:

<max> <size> <head> <current> <loop list>

For example, after:

x = Loop(4)

x.add(1)

x.add(3)

x.delete()

print(x)

"print(x)" prints out:

4 1 1 1 [None, 3, None, None]

For example:

Test Result
x = Loop(5)
print(x)
5 0 0 0 [None, None, None, None, None]
x = Loop(5)
x.add(3)
print(x)
5 1 0 0 [3, None, None, None, None]
x = Loop(3)
x.add(3)
x.add(2)
print(x)
3 2 0 1 [3, 2, None]
x = Loop(3)
x.add(3)
x.add(2)
x.delete()
print(x)
3 1 1 1 [None, 2, None]
x = Loop(3)
x.add(2)
x.add(5)
x.add(3)
x.delete()
x.add(7)
print(x)
3 3 1 0 [7, 5, 3]                     

Solutions

Expert Solution

'''
Python version : 2.7
Python program to create and test Loop class
'''

class Loop:
  
   def __init__(self, max):
      
       self.max = max
       self.loop = [None]*max
       self.head = 0
       self.current = 0
       self.size = 0
      
   def __str__(self):
       return str(self.max)+" "+str(self.size)+" "+str(self.head)+" "+str(self.current)+" "+str(self.loop)
      
   def add(self,element):
       # if empty loop, insert in index 0
       if self.empty():
           self.loop[0] = element
           self.head = 0
           self.current = 0
           self.size += 1
       # if full loop, nothing happens  
       elif self.size == self.max:
           return
       else:
           # get the next index for insertion
           self.current = (self.current + 1)%self.max
           # insert the element
           self.loop[self.current] = element
           self.size += 1 # increment the size
  
   def empty(self):
       return self.size == 0
      
   def count(self):
       return self.size
      
   def delete(self):
       # if loop is not empty
       if not self.empty():
           item = self.loop[self.head] # get the first element of the loop
           self.loop[self.head] = None # set the element to None
           self.size -= 1 # decrement the size
           # if loop is empty after deletion, reset head and current to 0
           if self.empty():
               self.head = 0
               self.current = 0
           else:   # update head to next element
               self.head = (self.head + 1)%self.max
           return item # return item
       return None

   def max(self):
       return self.max

# test the class      
def main():      

   x = Loop(5)
   print(x)
  
   x = Loop(5)
   x.add(3)
   print(x)

   x = Loop(3)
   x.add(3)
   x.add(2)
   print(x)

   x = Loop(3)
   x.add(3)
   x.add(2)
   x.delete()
   print(x)
  
   x = Loop(3)
   x.add(2)
   x.add(5)
   x.add(3)
   x.delete()
   x.add(7)
   print(x)

#call the main function  
main()  
#end of program
  
Code Screenshot:

Output:


Related Solutions

Python regex How to write the regex in Python that only include the contents within a...
Python regex How to write the regex in Python that only include the contents within a parentheses? e.g. "uio" [ek3k 0die] 4229834 return "ek3k 0die"
Write a python code which prints triangle of stars using a loop ( for loop )...
Write a python code which prints triangle of stars using a loop ( for loop ) Remember what 5 * "*" does The number of lines of output should be determined by the user. For example, if the user enters 3, your output should be: * ** *** If the user enters 6, the output should be: * ** *** **** ***** ****** You do NOT need to check for valid input in this program. You may assume the user...
Write a method that accepts a String object as an argument and displays its contents backward....
Write a method that accepts a String object as an argument and displays its contents backward. For instance, if the string argument is "gravity" the method should display "ytivarg". Demonstrate the method in a program that asks the user to input a string and then prints out the result of passing the string into the method. Sample Run java BackwardString Enter·a·string:Hello·world↵ dlrow·olleH↵
Python: What are the defintions of the three method below for a class Date? class Date(object):...
Python: What are the defintions of the three method below for a class Date? class Date(object): "Represents a Calendar date"    def __init__(self, day=0, month=0, year=0): "Initialize" pass def __str__(self): "Return a printable string representing the date: m/d/y" pass    def before(self, other): "Is this date before that?"
* Python * * Python Programming * Part 1: Product Class Write a class named Product...
* Python * * Python Programming * Part 1: Product Class Write a class named Product that holds data about an item in a retail store.   The class should store the following data in attributes: product id, item description, units in inventory, and price. Write the __init__ method to require all four attributes. Also write a __str__ method for debugging output.    Once you have written the class, write a main() function that creates three Product objects and stores the following...
Java Class Create a class with a main method. Write code including a loop that will...
Java Class Create a class with a main method. Write code including a loop that will display the first n positive odd integers and compute and display their sum. Read the value for n from the user and display the result to the screen.
What are the contents of the array after the for-loop in the following code?
(IN C)What are the contents of the array after the for-loop in the following code?int array[ SIZE ][ SIZE ] = { { 4, 5, 6, 7, 8 },{ 1, 2, 3, 4, 5 },{ 3, 6, 7, 8, 9 },{ 2, 3, 4, 5, 6 },{ 5, 6, 7, 8, 9 } };int i;int *ptr = array[ 0 ];for( i = 0; i < SIZE * SIZE; i++ ) {if( i % SIZE < 2 ) {*( ptr +...
Python Write a for loop with a range function and format output as currency Use an...
Python Write a for loop with a range function and format output as currency Use an input statement to ask the user for # of iterations using the prompt: #? [space after the ?] & assign to a variable Convert the variable to an integer Use a for loop and a range function to display all whole numbers from 1 to the user entered number Display the value of the item variable on screen in each iteration in the following...
Write a Python program that has a loop to continuously ask the user for a number,...
Write a Python program that has a loop to continuously ask the user for a number, terminating the loop when the number entered is -1. Inside the loop, 1.) display one asterisk(*) if the number is 1, 2.) two asterisk(**) if the number is 2 and 3.) "OTHER" if the number is any other number.
Write a program in PYTHON, using a while loop, that asks the user to enter the...
Write a program in PYTHON, using a while loop, that asks the user to enter the amount that they have budgeted for the month. The program should then prompt the user to enter their expenses for the month. The program should keep a running total. Once the user has finished entering their expenses the program should then display if the user is over or under budget. The output should display the monthly budget, the total expenses and whether the user...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT