Taking a queue of integers and making copies of that element - python

"Write a function named stutter that accepts a queue of integers as a parameter and replaces every element of the queue with two copies of that element in the original queue."
Example:
q1 = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
stutter(q1)
while not queue.isempty():
print(queue.dequeue(), end=' ')
should give answer as "1 1 2 2 3 3"
class Queue:
def __init__(self):
self.items = []
def is_empty(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)
def check_empty(self):
if self.items == []:
return True
def stutter(Q):
queue=Queue()
stack = Stack()
while not queue.isempty():
stack.push(queue.dequeue())
while not stack.isempty():
queue.enqueue(stack.pop())
That is the code that i have written, with that i can get it to print once and once only, i can't get it to duplicate and sort in order.

Try using this (can't test at the moment):
def stutter(queue):
# iterate all items
for _ in range(queue.size()):
# store item in local context
item = queue.dequeue()
# push two *references* to item into the queue
queue.enqueue(item)
queue.enqueue(item)
This will iterate all items once, immediately pushing two copes to the back of the queue. The first pushed items should be the first once this iteration is over.
Notice that objects will be not be duplicated,and there will be two references to the same object in the queue.
Tip: there is already a queue implementation in Python. You can use it by importing queue

In [17]:
def stutter(q):
for i in range(q.size()):
elm = q.dequeue()
q.enqueue(elm)
q.enqueue(elm)
In [18]:
q1 = Queue()
q1.enqueue(1)
q1.enqueue(2)
q1.enqueue(3)
stutter(q1)
print q1
[3, 3, 2, 2, 1, 1]
Note, I added a str method to the Queue class to see results.
class Queue:
# SAME AS BEFORE
def __str__(self):
return str(self.items)
You can also cheat because python does not have private instance variables. I would not recommend it as an option.
def stutter(q):
q.items = sorted([elm for elm in q.items] + [elm for elm in q.items])
If you want to return using the desired output:
q1 = Queue()
q1.enqueue(1)
q1.enqueue(2)
q1.enqueue(3)
stutter(q1)
print(' '.join([str(elm) for elm in q1.items]))
1 1 2 2 3 3

Related

how do i access class variable in class methods?

i have been trying to access the this self.arr instance in below methods.
when i call the main() it returns the wanted output but when i try call other methods to accessing the same list ,it just returns the empty list
class PaginationHelper:
# The constructor takes in an self.self.array of items and a integer indicating
# how many items fit within a single page
def __init__(self, collection, items_per_page):
self.c = collection
self.item_per_page = items_per_page
self.arr = []
def main(self):
k = 0
# i dont kow if below line perfectly creates no. of pages
count = len(self.c) % self.item_per_page
for i in range(count): # this for loop appends the number of pages " [ ] " in main list
self.arr.append([])
for x in range(len(self.c)):
self.arr[k].append(self.c[x]) # now this line fills the pages with items
if len(self.arr[k]) >= self.item_per_page:
k+=1 # when length of the given page exceeds the limit (item_per_page)
#then k += 1 means iernate on new page in main list
for z in range(len(self.arr)):
if len(self.arr[z])<0: self.arr.remove(self.self.arr[z])
print(self.arr)
def item_count(self):
print(self.arr)
return len(self.c)
def page_count(self):
print(self.arr)
return len(self.arr)
def page_item_count(self,page_index):
pass
def page_index(self,item_index):
print(self.arr)
return len(self.self.arr[item_index])
arr = ("a","b","c","d","e","f")
p = PaginationHelper(arr,4)
print(p.page_count())

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-

How can I create my own list iterable without even using subclass?

I am learning Python and have developed few web applications etc. Now, I want to dig deeper and learn about the under the hood workings of Python. For that, I would like to make my own list iterable. Here is my effort so far:
class CustomList:
def __init__(self,*args):
self.nums=args
self.count=0
i=0
for arg in args:
i+=1
self.total=i
def __iter__(self):
return self
def __next__(self):
if self.count >= self.total:
raise StopIteration
self.count+=1
mylist=CustomList(1,2,3,4)
for item in mylist:
print(item)
Now, in my next function, I am unsure how to iterate through my self.nums so that my print(item) prints each item in the self.nums one by one.
I don't really want to use anything related to len(), append() etc. I want to create them on my own. So that's the future plan. For now, I can't even iterate through the user given *args.
You need to go back another level. args in your MyList(*args) is already an iterable.
Each list item needs to explicitly point to the next one. So each list item needs a record of the next pointer and the data associated with it. This could be a dict but then MyList.append would need to explicitly access the records. For me the MyListItem class is clearer.
class MyListItem:
def __init__(self, data):
self.next = None
self.data = data
def link_to(self, child):
self.next = child
The MyList class can then use this as the nodes in it's list structure. There may be better implementations but this is the most basic I can get to.
class MyList:
def __init__(self):
""" Create the list header record, initialised to an empty list. """
self.top = None
self.bottom = None
self.curr = None # Used to iterate through the list.
def append(self, data):
node = MyListItem(data) # Create the List item
if self.top is None: # If the list is empty point top to node
self.top = node
else:
self.bottom.link_to(node) # Otherwise point the bottom node to the new node
self.bottom = node # Point the bottom to the new node
def __iter__(self):
self.curr = self.top # Initialise the current pointer to top
return self
def __next__(self):
if self.curr: # If the curr pointer is not None
res = self.curr.data # Get the data
self.curr = self.curr.next # Set curr to next
return res # Return the data
else:
raise StopIteration
Test it
test = MyList()
test.append(1)
test.append('Two')
test.append([1, 2, 3])
for node in test:
print(node)
1
Two
[1, 2, 3]

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")

how to implement a queue-like container with sort function

I want to a fixed length list-like container, it should have a sorted()-like function that I can use to sort it,I think there should also a function I can use it to detect whether the numbers of items in it reaches the length of the container , because if the numbers of items in it reaches the length(fixed) of the container,I want to process the data in it .Is there a container in Python like this ?If not, what base container should be used to implement such container?
the container is similar to queue ,but queue doesn't have a sort function
You can make your own container class if you want. Below is a very simplistic sample that may point you in the right direction.
class MyContainer:
def __init__(self, size, key=None, func=None):
self.size = size
self.items = []
self.key = key
self.func = func
def add_item(self, item):
if not self.is_full():
self.items.append(item)
else:
# Handle cases where the container is full, by raising an exception
# or printing an error message
#raise Exception('The container is full')
print("Container is full")
return
if len(self.items) == self.size:
self.sort_items(self.key)
self.process_items(self.sort)
def is_full(self):
return len(self.items) >= self.size
def sort_items(self, key):
self.items = sorted(self.items, key=key)
def process_items(self, func):
self.items = map(func, self.items)
Calling this function with key=lamba x: len(x) and func=str.lower will sort the list depending on the length of your items and convert all strings to lowercase.
>> c = MyContainer(3, key=lambda x: len(x), func=str.lower)
>> c.add_item('a')
>> c.add_item('aBcD')
>> c.add_item('ab')
>> print(c.items)
['a', 'ab', 'abcd']
It sounds like a PriorityQueue fits the spec. This allows items to be added to the queue in any order (up to a maximum), but they are then taken off the queue in sorted order:
import queue, random
items = list(range(15))
random.shuffle(items)
pq = queue.PriorityQueue(5)
while items:
pq.put_nowait(items.pop())
if pq.full():
print('processing...')
while not pq.empty():
print(pq.get_nowait())
print()
Output:
processing...
0
4
5
8
14
processing...
1
2
10
11
13
processing...
3
6
7
9
12

Categories