LinkedQueues and simulated printer - python

I am aware that there is another post asking about simulated printers but I didn't find any actual answers to my own question there.
class LinkedQueue :
class _Node :
__slots__ = '_element', '_next'
def __init__(self, element, next = None):
self._element = element
self._next = next
def __init__(self) :
self._head = None
self._tail = None
self._size = 0
def __len__(self) :
return self._size
def is_empty(self) :
return self._size == 0
def first(self) :
if self.is_empty() :
raise Empty('Queue is empty')
return self._head._element
def dequeue(self) :
if self.is_empty():
raise Empty('Queue is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty() :
self._tail = None
return answer
def enqueue(self, e) :
newest = self._Node(e,None)
if self.is_empty() :
self._head = newest
else :
self._tail._next = newest
self._tail = newest
self._size += 1
class Printer:
def __init__(self, name, job_queue):
self._name = name
self._job_queue
self._current_job = None
class Empty(Exception) :
pass
def main():
p_jobs = LinkedQueue()
red = Printer("Red", p_jobs) # Creates Printer Red
green = Printer("Green", p_jobs) # Creates Printer Green
print("\nOptions:\n 1. Add Job \n 2. Print Pages \n 3. Status \
\n 4. Quit")
i = 0
while True:
n = str(input("\nChoice (Type the number): "))
if n == '1': # Add Job
i += 1
p = int(input("\nHow many pages? "))
j = p_jobs.job_list(i,p,next)
p_jobs.enqueue(j)
if n == '2': # Print Job
print()
p_jobs.dequeue()
i -= 1
if n == '3': # Status
print()
if n == '4': # Quit
print("\nGoodbye!")
break
This is the provided code for us. We are supposed to simulate two printers that print out pages from jobs using LinkedQueue and Node.
I have the main function barebones w/c consists of 4 options:
Add Job, Print Jobs, Status, and Quit
I have trouble understanding how to use (refer) to the enqueue and dequeue methods. Can somebody break down each part of this program so I can at least understand where to start. I also would appreciate any hints that tell me where to go from here. Thank you.
EDIT: I added my main function w/c is basically just a UI

While this is by no means a complete answer, it shows how to print out what's currently in a LinkedQueue instance.
First, add the following method to the class. It will allow the contents to be iterated.
class LinkedQueue:
def __iter__(self):
if self.is_empty():
return None # No jobs in print queue.
cur = self._head
while cur:
yield cur._element
cur = cur._next
Here's something demonstrating how to use it:
def test():
q = LinkedQueue() # Create a queue.
# Add some jobs to the LinkedQueue.
for j in range(3):
pages = randint(1, 10)
q.enqueue(('job #{}'.format(j), pages))
# Show what's currently in the LinkedQueue.
for v in q:
print(v)
# Modify the LinkedQueue and then show what's left in it.
j = q.dequeue()
print('\nafter removing one job')
for v in q:
print(v)

Related

I can only push two values onto the stack array?

I can only push two values onto the stack array that I have created when I use the myPush() function. The reason I need to do it this way is because I am not allowed to use the built-in stack functions. Plus I have to use an array not a lit. Thank you.
I can only push two values onto the stack array that I have created when I use the myPush() function. The reason I need to do it this way is because I am not allowed to use the built-in stack functions. Plus I have to use an array not a lit. Thank you.
class Stack:
def __init__(self, data):
if data > 0:
self.stack = [0] * data
self.top = -1
self.stack[self.top] = self.stack[-1]
elif data <= 0:
self.stack = [0] * 10
self.top = -1
def showStack(self):
for i in self.stack:
print(i, end=" ")
return
def isEmpty(self):
return self.stack == []
def myEmpty(self): #complete this function
return # just a placeholder
def push(self, data):
self.stack.append(data)
def myPush(self, data):
if data == 0:
print("You did not enter a value.")
elif self.sizeStack() <= 10:
current = self.stack[stack.top]
self.stack[stack.top] = data
self.stack[stack.top - 1] = current
def pop(self):
data = self.stack[-1]
del self.stack[-1]
return data
def myPop(self): #complete this function
return # just a placeholder
def myPeek(self):
temp = self.top
return temp
def sizeStack(self):
return len(self.stack)
userVal = int(input("Enter the size of the stack: "))
stack = Stack(userVal)
while True:
print('\n1 display the stack')
print('2 add a value to the stack')
print('3 check the value at the top of the stack')
print('4 remove the value at the top of the stack')
print('5 check if the stack is empty')
print('99 quit')
option = int(input("Enter your choice: "))
if option == 1:
stack.showStack()
elif option == 2:
temp = int(input("Enter a number to add to the stack: "))
stack.myPush(temp)
elif option == 3:
print(stack.peek())
elif option == 99:
break
else:
print('Wrong option')
print
try defining a some customized functions that map to your list. Read up on customization here
class stack:
def __init__(self, data):
self.stack = [0] * data
self.top = -1
# whatever you want to do to init the list
def __str__(self): # replaces your showstack function now just use print(stack)
return self.stack
def __iter__(self): # creates an iterator you can use
return iter(self.stack)
def __len__(self): # replaces your sizestack function
return len(self.stack)
basically just adjust the methods you need.

Storing actions in a stack for 'undo' purpose

Because stack allows to either push or pop, it is suitable to redo actions by just simply popping the latest action by the user. I have a stack class where:
class Node:
def __init__(self,item,the_next = None):
self.item = item
self.next = the_next
def __str__(self):
return str(self.item)
class LinkedStack:
def __init__(self):
self.top = None
self.count = 0
def __len__(self):
return self.count
def is_empty(self):
return self.count == 0
def isFull(self):
return False
def reset(self):
self.top = None
self.count = 0
def __str__(self):
current = self.top
ans = ""
while not (current is None):
ans += str(current)
ans += '\n'
current = current.next
return ans
def _get_node(self,index):
if 0<= index< len(self):
current = self.top
while index>0:
current = current.next
index -=1
return current
def pop(self):
if self.is_empty():
raise StopIteration("Stack is empty")
output = self.top.item
self.top = self.top.next
self.count -=1
return output
def push(self,item):
newNode = Node(item)
newNode.next = self.top
self.top = newNode
self.count +=1
if __name__ == "__main__":
L = LinkedStack()
and in another file, i import the stack from above and try to implement the undo action.
from Stack import LinkedStack
class Editor:
def __init__(self):
self.count = 0
self._list = LinkedList()
self._stack = LinkedStack()
def command(self,userCommand):
userCommand = userCommand.split(' ')
try:
if userCommand[0] == 'insert':
position = int(userCommand[1])
if len(userCommand) ==1:
raise Exception('no num is given')
textInput = input("Enter your text:")
self._stack.push(self.insertText(position,textInput)) #I'm thinking of adding the action into the stack by pushing it.
print(self._list)
pass
except Exception:
print('?')
if userCommand[0] == 'undo': #here if they choose to undo, by right i just pop the last action from the stack
self._stack.pop()
if __name__ == '__main__':
myCommand = Editor()
while True:
command = input('Enter an option:')
if command.lower() == 'quit':
break
else:
myCommand.command(command)
because I'm merely undoing actions, i thought of adding the command actions into a stack. if you take a look at the insert command above, where i added a comment, am i doing it correctly? Because I'm running out of ideas.
By the way, the insertText is a function which is working and I'm not planning to paste it here as it's getting lengthy. LinkedList() is just a linked list class i imported from another file as well.
The 'undo' doesn't seemed to revert the state. For example, if my LinkedList() contains:
1
2
3
4
None
and if i use the insert function to insert another number, 7 at index 1
1
7
2
3
4
None
and if i undo the action, I'm supposed to have:
1
2
3
4
None

How to print return value of method in Python?

class Queue():
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def Enqueue(self,item):
return self.items.insert(0, item)
def Size(self):
return len(self.items)
def Dequeue(self):
return self.items.pop()
Q = Queue()
def Hotpot(namelist,num):
for name in namelist:
Q.Enqueue(name)
while Q.Size() > 1:
for i in range(num):
Q.Enqueue(Q.Dequeue())
Q.Dequeue()
return Q.Dequeue() # I would like to print and see what is getting removed, I tried with x = Q.Dequeue(), print x and print Q.Dequeue() but im getting "None"
print Hotpot(['A','B','C','D','E','F'],7)
Hi Team,
I am trying above code for checking Queue, here I would like to print which value is removing each cycle. While printing I am getting none oly, please help me what changes I have to do for my expectation.
If you want to know what's goingto be returned, you need to save it locally, print what you saved, then return what you saved. Something like:
x = Q.Dequeue()
print(x)
return x
Your code works for me, when you change Q.Dequeue() by print Q.Dequeue().
Better python would be:
from collections import deque
def hotspot(names, num):
queue = deque(reversed(names))
while len(queue)>1:
queue.rotate(num)
print queue.pop()
return queue.pop()
print hotspot(['A','B','C','D','E','F'], 7)

I am trying to implement a Skiplist using Python. Can you help me? Very simple

This is just a very simple code and my reference is from here: http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/Map/skip-list-impl.html#why-q
I think the insert function is okay but when I try to use the get() function, it doesn't return anything, instead it loops endlessly inside the searchEntry() part. I don't know what's wrong. In the insert() function, the searchEntry() operates well. It returns the reference to the floorEntry(k) entry containing a key that is smaller than the key that needs to be inserted in the skiplist. Please help me figure out the source of the error in the searchEntry() function. I'm sorry I'm not really good at this. Thank you!
from QuadLinkedList import QLLNode
import random
class Skippy:
def __init__(self):
self._p1 = QLLNode("MINUS_INF")
self._p2 = QLLNode("PLUS_INF")
self._head = self._p1
self._tail = self._p2
self._p1.setNext(self._p2)
self._p2.setPrev(self._p1)
self._height = 0
self._n = 0
def insert(self, key, value):
p = self.searchEntry(key)
print "p = " + str(p.getKey())
q = QLLNode(key, value)
q.setPrev(p)
q.setNext(p.getNext())
p.getNext().setPrev(q)
p.setNext(q)
i = 0
while random.randint(0,1) != 0:
if i >= self._height:
self._height += 1
newHead = QLLNode("MINUS_INF")
newTail = QLLNode("PLUS_INF")
newHead.setNext(newTail)
newHead.setDown(self._head)
newTail.setPrev(newHead)
newTail.setDown(self._tail)
self._head.setUp(newHead)
self._tail.setUp(newTail)
self._head = newHead
self._tail = newTail
while p.getUp() == None:
p = p.getPrev()
p = p.getUp()
e = QLLNode(key,None)
e.setPrev(p)
e.setNext(p.getNext())
e.setDown(q)
p.getNext().setPrev(e)
p.setNext(e)
q.setUp(e)
q = e
i += 1
self._n += 1
return None
def get(self, key):
p = self.searchEntry(key)
if key == p.getKey():
return p.getElement()
else:
return "There's None!"
def searchEntry(self, key):
p = self._head
while True:
while p.getNext().getKey() != "PLUS_INF" and p.getNext().getKey() <= key:
p = p.getNext()
if p.getDown() != None:
p = p.getDown()
else:
break
return p
The issue isn't in the code for searchEntry, which appears to have the correct logic. The problem is that the list structure is getting messed up. I believe the issue is with the code you have for adding a new level to the list in insert. Specifically this bit:
if i >= self._height: #make an empty level
self._height += 1
self._minus.setNext(self._plus)
self._minus.setDown(self._head)
self._plus.setPrev(self._minus)
self._plus.setDown(self._tail)
self._head.setUp(self._minus)
self._tail.setUp(self._plus)
self._head = self._minus
self._tail = self._plus
The thing that stands out to me about this code is that you're not creating any new nodes, just modifying existing ones, which is what is breaking your list structure. You need to create new head and tail nodes, I think, and link them into the top of the strucutre. (minus and plus are not part of the algorithm as described at your link, so I'm not sure what you're doing with them.) Probably you want something like this:
if i >= self._height: #make an empty level
self._height += 1
newHead = QLLNode("MINUS_INF")
newTail = QLLNode("PLUS_INF")
newHead.setNext(newTail)
newHead.setDown(self._head)
newTail.setPrev(newHead)
newTail.setDown(self._tail)
self._head.setUp(newHead)
self._head = newHead
self._tail.setUp(newTail)
self._tail = newTail

Stack data structure in python

I have 2 issues with the code below:
push(o) throws an exception TypeError: can only assign an iterable.
Should I throw an exception if pop() is invoked on an empty stack ?
class Stack(object):
def __init__(self):
self.storage = []
def isEmpty(self):
return len(self.storage) == 0
def push(self,p):
self.storage[:0] = p
def pop(self):
"""issue: throw exception?"""
return None
No need to jump through these loops, See 5.1.1 Using Lists as Stacks
If you insist on having methods isEmpty() and push() you can do:
class stack(list):
def push(self, item):
self.append(item)
def isEmpty(self):
return not self
You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose.
class Stack:
def __init__(self):
self.__storage = []
def isEmpty(self):
return len(self.__storage) == 0
def push(self,p):
self.__storage.append(p)
def pop(self):
return self.__storage.pop()
This way your interface works pretty much like list (same behavior on pop for example), except that you've locked it to ensure nobody messes with the internals.
I won't talk about the list structure as that's already been covered in this question. Instead I'll mention my preferred method for dealing with stacks:
I always use the Queue module. It supports FIFO and LIFO data structures and is thread safe.
See the docs for more info. It doesn't implement a isEmpty() function, it instead raises a Full or Empty exception if a push or pop can't be done.
Stack follows LIFO mechanism.You can create a list and do a normal append() to append the element to list and do pop() to retrieve the element out of the list which you just inserted.
Here is an example for stack class
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def isEmpty(self):
return len(self.items) == 0
class Stack:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self , item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[-1]
Create a stack
To create a new stack we can simply use Stack()
for example:
s=Stack()
"s" is the name of new stack
isEmpty
By using isEmpty() we can check our stack is empty or not
for example:
we have two stacks name s1=(0,1,4,5,6) and s2=()
if we use print(s1.isEmpty()) it will return False
if we use print(s2.isEmpty()) it will return True
push
By using push operation we can add items to top of the stack
we can add "6" to the stack name "s" using
s.push(6)
pop
we can use pop operation to remove and return the top item of a stack
if there is a stack name "s" with n amount items (n>0)
we can remove it's top most item by using
s.pop()
size
This operation will return how many items are in the stack
if there is a stack name "s" s=(1,2,3,4,5,3)
print(s.size())
will return "6"
peek
This operation returns the top item without removing it
print(s.peek())
"we can print items of the stack using print(s.items)"
class Stack:
def __init__(self):
self.stack = []
def pop(self):
if self.is_empty():
return None
else:
return self.stack.pop()
def push(self, d):
return self.stack.append(d)
def peek(self):
if self.is_empty():
return None
else:
return self.stack[-1]
def size(self):
return len(self.stack)
def is_empty(self):
return self.size() == 0
class stack:
def __init__(self,n):##constructor
self.no = n ##size of stack
self.Stack = [] ##list for store stack items
self.top = -1
def push(self):##push method
if self.top == self.no - 1 :##check full condition
print("Stack Overflow.....")
else:
n = int(input("enter an element :: "))
self.Stack.append(n) ## in list add stack items use of append method
self.top += 1##increment top by 1
def pop(self):## pop method
if self.top == -1: #check empty condition
print("Stack Underflow....")
else:
self.Stack.pop()## delete item from top of stack using pop method
self.top -= 1 ## decrement top by 1
def peep(self): ##peep method
print(self.top,"\t",self.Stack[-1]) ##display top item
def disp (self): #display method
if self.top == -1:# check empty condition
print("Stack Underflow....")
else:
print("TOP \tELEMENT")
for i in range(self.top,-1,-1): ## print items and top
print(i," \t",self.Stack[i])
n = int(input("Enter Size :: ")) # size of stack
stk = stack(n) ## object and pass n as size
while(True): ## loop for choice as a switch case
print(" 1: PUSH ")
print(" 2: POP ")
print(" 3: PEEP ")
print(" 4: PRINT ")
print(" 5: EXIT ")
option = int(input("enter your choice :: "))
if option == 1:
stk.push()
elif option == 2:
stk.pop()
elif option == 3:
stk.peep()
elif option == 4:
stk.disp()
elif option == 5:
print("you are exit!!!!!")
break
else:
print("Incorrect option")

Categories

Resources