using queue to add a shape in canvas - python

I was confused on how to add a shape using a queue in canvas. I'm trying to add a triangle. This is the code I've got. I'm getting an error >>> AttributeError: 'Queue' object has no attribute 'enqueue'
I've been trying this for awhile now and I thought I had the right idea, I just need some guidelines thanks!
from tkinter import *
import random
root = Tk()
from queue import *
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def size(self):
return len(self.items)
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
class Recta():
def __init__(self, height=60, width=80):
self.queue = Queue()
def create_buttons(self):
self.button5 = Button(self.frame, text = "Add Arc", command = self.random_arc)
self.button5.pack(side = 'left')
def random_arc(self):
w = random.randrange(45)
h = random.randrange(90)
self.queue.enqueue(self.canvas.create_arc(0,w,h,fill= "green"))
tes = Recta()
tes = Queue()
root.mainloop()

For the module queue I don't see a function enqueue().
There is queue.Queue.put(), though.
Update
Is it possible, that python is taking the "wrong" Queue, meaning the one from inside the module queue?
Update
Maybe start by renaming your class "Queue" to something different like "Queue1".
Or just use the queue.Queue from the module.
Update
If you want to use a stack, just use list funcitonalities, no class Stack is necessary:
stack = list()
stack.append('item1')
stack.append('item2')
stack.append('item3')
print stack.pop()
>>> 'item3'
By just using .pop() you make it appear to be a stack.

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-

I implement a stack in python, however the "push" method doesn't work

I'm still new to python, so I'm practicing implementing a stack, and I don't understand why the push method doesn't work. My code is the following:
class Stack:
def __init__(self):
self.top = None
self.size = 0
def isEmpty(self):
return self.top == None
def push(self, value):
node = Node(value, self.top)
self.top = node
self.size += 1
def pop(self):
assert not self.isEmpty, "Error: The stack is empty"
node = self.top
self.top = self.top.next
return node.value
class Node:
def __init__(self, value, link):
self.value = value
self.next = link
def main():
stack = Stack()
assert stack.isEmpty, "--> Error: isEmpty"
stack.push(1)
assert not stack.isEmpty, "--> Error: not isEmpty"
print(stack.pop())
if __name__ == "__main__":
main()
This is the exit:
File "c:", line 33, in main
assert not stack.isEmpty, "--> Error: not isEmpty"
AssertionError: --> Error: not isEmpty
stack.isEmpty is a function, while stack.isEmpty() is a function call (returning a Boolean).
Edit: If you want an attribute isEmpty, declare one within __init__() and just make sure you update it whenever a change is made to the object. That way you can refer to stack.isEmpty without needing to call a function. That's more of personal preference.

Python thread class instance change a variable for all instances

I'm new to python threads and I can't find any answers for that. If it is a duplicate question sorry for that.
I have a thread class like this:
class Ant(Thread):
def __init__(self, start_item, possible_items, backpack_limit, pheromone_map, alpha, beta, eta):
Thread.__init__(self)
self.start_item = start_item
self.item = start_item
self.possible_items = possible_items
self.selected_items = []
self.backpack_limit = backpack_limit
self.weight_sum = 0
self.backpack_value = 0
self.pheromone_map = pheromone_map
self.alpha = alpha
self.beta = beta
self.eta = eta # (weight/value)
# append start location to route, before doing random walk
self.add_backpack(start_item)
self.tour_complete = False
def run(self):
while self.possible_items and self.is_remaining_space_feasible():
next_item = self.pick_item()
self.item = next_item
self.add_backpack(next_item)
self.tour_complete = True
def add_backpack(self, next_item):
self.update_items(next_item)
self.update_backpack(next_item)
def update_items(self, next_item):
self.selected_items.append(next_item)
self.possible_items.remove(next_item)
def update_backpack(self, next_item):
self.weight_sum += next_item.get_weight()
self.backpack_value += next_item.get_value()
and I create bunch of instances in another class like this:
ants = [Ant(self.items[random.randint(0, len(self.items) - 1)], self.items, self.backpack_limit, self.pheromone_matrix, self.alpha, self.beta, self.eta) for _ in range(self.ant_count)]
As you can see when I create an ant instance it's called add_backpack function and at some point this piece of code work self.possible_items.remove(next_item) and the program finished the initialization step and create the next instance. But for the next instance possible_items already removed the item and this caused list.remove(x): x not in list error. I tried deep copying but it's doesn't work.

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

Creating stack class in Python

This implementation uses linked list instead of using the built-in list. Does anyone use which version is better for performance?
class Stack:
top = ''
def __init__(self,data=None,next=None):
self.data = data
self.next = next
def pop(self):
if self.top != None:
item = self.top.getvalue()
self.top = self.top.next
return item
else:
return
def push(self,data):
t = Stack(data)
t.next = self.top
self.top = t
def peek(self):
return self.top.getvalue()
def getvalue(self):
return self.data
s = Stack()
s.push('bottom')
s.push('middle')
s.push('top')
popped = s.pop()
print(popped)
top = s.peek()
print(top)
Outputs:
top
middle
A stack class based on the built-in list will have much better performance, e.g.
class StackEmptyError(Exception):
pass
class ListBasedStack(list):
push = list.append
def pop(self):
try:
return super(ListBasedStack, self).pop()
except IndexError:
raise StackEmptyError
def peek(self):
try:
return self[-1]
except IndexError:
raise StackEmptyError
Measure execution time with the timeit module:
>>> import timeit
>>> stmt = '''
s = Stack()
s.push('bottom')
s.push('middle')
s.push('top')
s.peek()
s.pop()'''
# test built-in list stack class
>>> timeit.repeat(stmt, 'from __main__ import ListBasedStack as Stack')
[1.4590871334075928, 1.4085769653320312, 1.3971672058105469]
# test OP stack class
>>> timeit.repeat(stmt, 'from __main__ import Stack')
[5.018421173095703, 4.971158981323242, 4.990453004837036]
The built-in list based class is approx 3.5 times faster than the linked list one.
And, if you are not fussy about having IndexError exceptions raised for Stack operations, it is faster still (approx 5 times faster):
class MinimalistStack(list):
push = list.append
def peek(self):
return self[-1]
>>> timeit.repeat(stmt, 'from __main__ import MinimalistStack as Stack')
[0.9379069805145264, 0.9144589900970459, 0.9160430431365967]

Categories