Queue implementation display function error - python

class Queue:
def __init__(self): '''initialization of function'''
self.items = []
def is_empty(self): '''Checking if queue is empty or not'''
return self.items == []
def enqueue(self, data): '''Adding value '''
self.items.append(data)
def dequeue(self): ''' Removing value'''
return self.items.pop(0)
def dis(self): '''Printing the stored item in queue'''
print(items)
After that initialization of Queue:
q = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('dis')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
q.enqueue(int(do[1]))
elif operation == 'dequeue':
if q.is_empty():
print('Queue is empty.')
else:
print('Dequeued value: ', q.dequeue())
elif operation == 'dis':
q.dis()
elif operation == 'quit':
break
else:
print("Enter the correct operation")
I'm not able to display the items which are enqueued in the Queue. How could I use dis() method to display items in it?

Think you should print self.items (instead of items)
def dis(self): '''Printing the stored item in queue'''
print(self.items)
That'll output the list using standard formatting, not very pretty so you'll probably want to add some extra logic for pretty-printing.
If you want to restrict the queue size, you could do this by simply ignoring items past a certain limit. For this you'll need to implement a limit, along with logic for checking the limit. For example:
class Queue:
def __init__(self, size=8): '''initialization of function'''
self.items = []
self.size = size
def is_empty(self): '''Checking if queue is empty or not'''
return self.items == []
def enqueue(self, data): '''Adding value '''
if len(self.items) < self.size:
self.items.append(data)
else:
pass # behavior when queue is already full
def dequeue(self): ''' Removing value'''
return self.items.pop(0)
def dis(self): '''Printing the stored item in queue'''
print(items)

class Queue:
items=[]
size=5
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
def dis(self):
print(self.items)
def is_full(self):
if (len(self.zitems)>5):
print("Queue is full")
else:
print("Not full")
Inizialize the items=[] and in dis method add self.items.Also, you could check if the size of the queue is full or not

Related

How do I "run" a function that is in a queue?

Basically I created a queue in Python with some functions (that the user put in the order he wants) and now I want to execute this functions in order, but I really didn't find what which order do that.
The queue:
class Queue:
def __init__(self):
self.elements = []
def enqueue(self, data):
self.elements.append(data)
return data
def dequeue(self):
return self.elements.pop(0)
def rear(self):
return self.elements[-1]
def front(self):
return self.elements[0]
def is_empty(self):
return len(self.elements) == 0
The functions:
if (escolha=='2'):
print("Type your hotkey. Ex: alt+tab+ [3 keys maximum]")
my_var = input("")
my_var = my_var.split('+')
def hotchave():
pyautogui.hotkey(str(my_var[0]),str(my_var[1]),str(my_var[2]))
queue.enqueue(hotchave)
if (escolha=='3'):
write=input('What will be written?: ')
def escrever():
pyautogui.write(write)
queue.enqueue(escrever)
I already tried things like return, front but didn't seem to work.
There's several different ways to do what you want, some of which require to modify your class. Since you say you would like to retrieve and run multiple functions from the queue, I would suggest making it possible to iterate its current contents, which can be done simply by adding an __iter__() method to the class.
The following shows how to do that, along with how to make use of it.
class Queue:
def __init__(self):
self.elements = []
def enqueue(self, data):
self.elements.append(data)
return data
def dequeue(self):
return self.elements.pop(0)
def rear(self):
return self.elements[-1]
def front(self):
return self.elements[0]
def is_empty(self):
return len(self.elements) == 0
def __iter__(self):
'''Iterate current contents.'''
return (elem for elem in self.elements)
Sample usage:
queue = Queue()
my_var = 'alt+shift+k'
my_var = my_var.split('+')
def hotchave():
print('vars:', str(my_var[0]), str(my_var[1]), str(my_var[2]))
queue.enqueue(hotchave)
write = 'This will be written'
def escrever():
print(write)
queue.enqueue(escrever)
# Execute commands in Queue.
for command in queue:
command()
print('-fini-')
Output:
vars: alt shift k
This will be written
-fini-

Python: CircularQueue print items from begin to end of Queue

I am trying to implement Circular Queue in python and trying implement str(self) that print all the elements from the queue from the beginning to the end.When I print out the list, it does not give the whole list of items in the queue.
I am splicing the items from the self.items from the front and going till the end of the list.
class CircularQueue:
def __init__(self,capacity):
self.items =[None]*capacity
self.MAX_QUEUE = capacity
self.front = 0
self.back = self.MAX_QUEUE - 1
self.count = 0
def is_full(self):
return self.count == self.MAX_QUEUE
def is_empty(self):
return self.count == 0
def enqueue(self,item):
if not self.is_full():
self.back = (self.back+1)%self.MAX_QUEUE
self.items[self.back] = item
self.count +=1
else:
raise IndexError("The queue is full.")
def dequeue(self):
if not self.is_empty():
item = self.items[self.front]
self.front =(self.front+1)% self.MAX_QUEUE
self.count -=1
return item
else:
raise IndexError("The queue is empty.")
def peek(self):
if not self.is_empty():
item = self.items[self.front]
return item
else:
raise IndexError("The queue is empty.")
def __str__(self):
my_list = []
for i in self.items[self.front:]:
my_list.append(i)
return str(my_list)
q = CircularQueue(8)
q.enqueue(5)
q.enqueue(2)
q.enqueue(1)
q.enqueue(7)
q.enqueue(9)
q.dequeue()
q.dequeue()
q.dequeue()
q.dequeue()
q.dequeue()
q.enqueue(2)
q.enqueue(4)
q.enqueue(1)
q.enqueue(7)
q.enqueue(6)
q.enqueue(3)
print(q)
Expected result:
[2, 4, 1, 7, 6, 3]
Got:
[2,4,1]
It looks like your problem is that you only add in the elements from the front of the circular array to the end of the underlying list implementation. What you really want to do is copy from front to end, and then from beginning to back.
This gives me the correct output
def __str__(self):
my_list = []
for i in self.items[self.front:]:
my_list.append(i)
for i in self.items[:self.back+1]:
my_list.append(i)
return str(my_list)
Hope that helps! Also, you might want to consider using cycle from itertools.

How to use Iterator that traverses the doubly linked list and skips null nodes

Since the doubly linked list has two dummy nodes, one is the head and the other one is the tail. I can skip the dummy tail node by self.__current == None: raise StopIteration, but I don't know how to pass the dummy head nodes and continue traverse the following node.
class LinkedListDLL:
def __init__(self):
self.__head = NodeDLL(None)
self.__head.set_next(self.__head)
self.__head.set_prev(self.__head)
self.__count = 0
def size(self):
return self.__count;
def is_empty(self):
return self.__count == 0
def add_before(self, item, curr):
new_node = NodeDLL(item)
new_node.set_next(curr)
new_node.set_prev(curr.get_prev())
curr.set_prev(new_node)
new_node.get_prev().set_next(new_node)
self.__count += 1
def add_to_head(self, item):
self.add_before(item, self.__head.get_next())
def add_to_tail(self, item):
self.add_before(item, self.__head)
def remove_from_head(self):
self.remove(self.__head.get_next())
def remove_from_tail(self):
self.remove(self.__head.get_prev())
def remove(self, curr):
curr.get_prev().set_next(curr.get_next())
curr.get_next().set_prev(curr.get_prev())
self.__count -= 1
def __iter__(self):
return LinkedListIterator(self.__head)
class LinkedListIterator:
def __init__(self, head):
self.__current = head
def __next__(self):
if self.__current == None :
raise StopIteration
else:
item = self.__current.set_data.get_next()
self.__current = self.__current.get_next()
return item
You should refactor your code keeping in mind that NodeDLL(None) may not be the same as None. With that done:
def __next__(self):
if not self.__current.get_next():
raise StopIteration
#Skips first value in list, i.e. head
self.__current = self.__current.get_next()
return self.__current

Understanding Stacks and Queues in python

So i was given this question. Consider the Stack and the Queue class with standard set of operations. Using the Stack and Queue class, what items are contained in them just before the mysteryFunction is called AND just after the mysteryFunction is called?
Here is the code:
def mysteryFunction(s, q):
q.enqueue('csc148')
q.enqueue(True)
q.enqueue(q.front())
q.enqueue('abstract data type')
for i in range(q.size()):
s.push(q.dequeue())
while not s.is_empty():
q.enqueue(s.pop())
if __name__ == '__main__':
s=Stack()
q=Queue()
#About to call mysteryFunction
#What are contents of s and q at this point?
mysteryFunction(s, q)
#mysteryFunction has been called.
#What are contents of s and q at this point?
I'm having trouble understanding object oriented programming as i'm new to this topic. Is there any link that breaks down Stacks and Queues and what they do?
In general, stacks are LIFO and queues are FIFO.
In Python, you can use the collections module to experiment with stacks and queues:
>>> from collections import deque
>>> stack = deque()
>>> stack.append(10)
>>> stack.append(20)
>>> stack.append(30)
>>> stack
deque([10, 20, 30])
>>> stack.pop() # LIFO
30
>>> stack.pop()
20
>>>
>>> queue = deque()
>>> queue.append(10)
>>> queue.append(20)
>>> queue.append(30)
>>> queue
deque([10, 20, 30])
>>> queue.popleft() # FIFO
10
>>> queue.popleft()
20
See following links for more information:
Stack
Queue
Visually these two data structures can be seen in a following way:
Stack:
Description:
There are variations of this data structure. However, in simple terms - as one can observe in the image provided, when you add to this data structure you place on top of what is already there and when you remove you also take from the top. You can view it as a stack of books which you go through one by one starting from the top and all the way down.
Queue
Description:
There are also variations on this particular data structure, however in simple terms - as you can see in the image provided, when you add to this data structure the new element goes in the begining and when you remove its the last element from the list which is being removed. You can imagine it as a queue you got in a shop where you stand behind a lot of people waiting for your turn to come to the counter to pay for your items.
To test this line by line, here are implementations of the classes (wrappers around deque) that are used in the task:
from collections import deque
class Queue(deque):
enqueue = deque.append
dequeue = deque.popleft
def front(self):
return self[-1]
def size(self):
return len(self)
class Stack(deque):
push = deque.append
def is_empty(self):
return not self
STACK #LIFO
class stack(object):
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 peek(self):
return self.items[len(self.items) - 1]
def size(self):
return (len(self.items))
s = stack()
print (s.isEmpty())
>> True
s.push(1)
s.push('3')
s.peek()
>>'3'
s.size()
>> 2
Queue #FIFO
class Queue(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items==[]
def enqueue(self,item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return (len(self.items))
q = Queue()
q.isEmpty()
>>True
q.enqueue(1)
q.enqueue(2)
q.dequeue()
>>1
The first code explains about the stack , we need to create a list and while pushing the element use append and fill the list , similar to what we have in array stack. While pop , pop out the end from where you pushed it.
class Stack:
def __init__(self):
self.stack = []
def push_element(self,dataval):
self.stack.append(dataval)
return self.stack
def pop_element(self):
if len(self.stack) ==0:
print("Stack is empty")
else:
self.stack.pop()
return self.stack
def peek_element(self):
return self.stack[0]
class Queue:
def __init__(self):
self.stack = []
def push_ele(self,data):
self.stack.append(data)
def pop_ele(self):
self.stack.pop(0)
def display(self):
print(self.stack)
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")

Taking elements from list and putting them in a stack with python

This is what i currently have and says that it is missing one argument when it tries to push i
this is the class that I have for this code
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, a):
self._data.append(a)
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data[-1]
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data.pop()
def reverselist():
expression = input("Enter whatever: ")
stacks = ArrayStack
listofstuff = []
for item in expression:
listofstuff.append(item)
print(listofstuff)
for token in listofstuff:
i = str(token)
stacks.push(i)
You need an instance of ArrayStack, not the class itself, change for ArrayStack(), this calls the constructor of your class.
def reverselist():
expression = input("Enter whatever: ")
stacks = ArrayStack()
listofstuff = []
for item in expression:
listofstuff.append(item)
print(listofstuff)
for token in listofstuff:
i = str(token)
stacks.push(i)

Categories