creating a class in python - error - python

The program I am creating should run a queue class however errors occur that append is not able to be used in the class as it does not exist, even thought it is set to a string. Could someone help me understand why I am receiving these errors?
class Queue:
def queue(self):
self.queue = []
self.out_stack = []
def enqueue(self, other='string'):
self.enqeue = self.queue.append(other)
def dequeue(self):
if not self.out_stack:
while self.queue:
self.dequeue = self.out_stack.append(self.queue.pop(1))
return self.dequeue
def isEmpty(self):
return self.queue == []

When you create an instance variable self.queue, you are shadowing the method defined by def queue(self):
It looks like that method should perhaps be your __init__ method
class Queue:
def __init__(self):
self.queue = []
self.out_stack = []
def enqueue(self, other='string'):
self.queue.append(other)
def dequeue(self): # what is this method supposed to do?
if not self.out_stack:
while self.queue:
self.dequeue = self.out_stack.append(self.queue.pop(1))
return self.dequeue
def isEmpty(self):
return self.queue == []
Now there is still a similar problem with self.dequeue being used as both a method and an attribute. I am not sure what you are trying to do there.

Related

Observer pattern updating after unsubscribing

I am currently trying to implement the observer design pattern on a List class. The list class is the subject, and a calculate class is the observer. The calculate class needs to observe the list class, and calculate the sum of the values in the list in the list class. However, when the observer unsubscribes from the List, it is still getting the updates. And if the observer subscribes to a new list, the list before unsubscribing is still showing. Does anyone have any tips to why this happens?
from abc import ABCMeta, abstractmethod
class Observer(metaclass = ABCMeta):
#abstractmethod
def update(self, data):
pass
class Subject(metaclass = ABCMeta):
#abstractmethod
def subscribe(self, observer):
pass
#abstractmethod
def unsubscribe(self, observer):
pass
#abstractmethod
def notify(self):
pass
class List(Subject):
def __init__(self):
self.__list = []
self._observers = set()
def add(self, data):
self.__list.append(data)
self.notify()
def subscribe(self, observer):
self._observers.add(observer)
def unsubscribe(self, observer):
self._observers.discard(observer)
def notify(self):
for obs in self._observers:
obs.update(self.__list)
class Calculate(Observer):
def __init__(self, lst):
self.__data = []
self._list = lst
self._list.subscribe(self)
def update(self, data):
self.__data = data
def calculate(self):
total = 0
for item in self.__data:
total += item
return total
def remove(self):
self._list.unsubscribe(self)
def attach(self, lst):
self._list.subscribe(self)
So, this is my test and the output i get:
first_list = List()
first_list.add(1)
list_observer = Calculate(first_list)
first_list.add(5)
list_observer.calculate()
This returns 6, which is correct. However, when i do this:
list_observer.remove()
first_list.add(5)
list_observer.calculate()
I get 11. Which in sense, is the correct calculation, but since the observer unsubscribed, why is it still getting the updates? I also tried subscribing to a new list, but the old data is still in there.
This has to do with the type of data you pass. The list of data is mutable. I can't explain it that well, but this answer is what you are looking for.
How do I pass a variable by reference?
You can fix it by doing this, you take a copy of the original object:
def update(self, data):
self.__data = data.copy()

python how to inherit parent stack

hey guys i am new to data structure and i havee been wondering how to inherit a parent class attributes.
I am trying to inherit the attributes of stack(parent) to stack3(child) but the error keeps popping up: TypeError: init() missing 1 required positional argument: '_Stack3__list'
Any help or suggestions would be appreciated!
class Stack:
def __init__(self):
self.__list= []
def isEmpty(self):
return self.__list == []
def size(self):
return len(self.__list)
def clear(self):
self.__list.clear()
def push(self, item):
self.__list.append(item)
def pop(self):
if self.isEmpty():
return None
else:
return self.__list.pop()
def get(self):
if self.isEmpty():
return None
else:
return self.__list[-1]
def __str__(self):
output = '<'
for i in range( len(self.__list) ):
item = self.__list[i]
if i < len(self.__list)-1 :
output += f'{str(item)}, '
else:
output += f'{str(item)}'
output += '>'
return output
class Stack3(Stack):
def __init__(self,__list):
self.__list = __list
super().__init__(self.__list)
def printMe(self):
super().__str__()
s = Stack3()
print(s.pop())
for i in range(1,6):
s.push(i)
print('Content of stack =',s)
print('Item at top=',s.get())
print('Size=', s.size())
while not s.isEmpty():
print(s.pop())
print(s)
If you want to pass all arguments from Stack3.__init__ to Stack. __init__ use:
class Stack3(Stack):
def __init__(self,*args, **kwargs):
super().__init__(*args, **kwargs)
see here for a detailed explanation of *args and **kwargs usage.

How to create a simple class Queue in python 3.6?

I'm beginner. Here is my code:
class Queue:
def __init__(self):
self.queue = []
def dequeue(self):
self.queue.pop(O)
def enqueue(self,element):
self.queue.append(element)
q=Queue()
q.enqueue('dog')
print(q)
But! I see this:
<__main__.Queue object at 0x00A3FC10>
What is it? How to create this class than?
That is the default display representation of an instance of your class. The default is to display the class name and the address of its instance in memory. You can override __repr__ and __str__ to customize the representation:
class Queue:
def __init__(self):
self.queue = []
def dequeue(self):
return self.queue.pop(0) # probably want to return what you dequeue.
def enqueue(self,element):
self.queue.append(element)
# Customize debug representation...you want to know it is a Queue and what is in it.
def __repr__(self):
return f'Queue({self.queue})'
# Customize print representation...may just want to see the list.
def __str__(self):
return f'{self.queue}'
q=Queue()
q.enqueue('dog')
q.enqueue('cat')
print(repr(q))
print(q)
print(f'popped {q.dequeue()}')
print(q)
Output:
Queue(['dog', 'cat'])
['dog', 'cat']
popped dog
['cat']

Typerror while accessing parent class data members

I am trying to create a queue using two stacks and below is my code :-
class Stack1(object):
def __init__(self):
super(Stack1, self).__init__()
self.stack1 = []
def push(self, item):
self.stack1.append(item)
def pop(self):
self.popped_value = self.stack1.pop()
print("popped_value parent", self.popped_value)
return self.popped_value
def peek(self):
try:
return self.stack1[len(stack1)-1]
except:
print("Cannot peek into stack 1")
def is_empty(self):
if len(self.stack1) == 0:
return True
else:
return False
def display(self):
print(self.stack1)
class Stack2(Stack1):
def __init__(self):
super(Stack2).__init__()
self.stack2 = []
def push(self, popped):
self.popped = popped
return self.stack2.append(self.popped)
def pop(self):
return self.stack2.pop()
def peek(self):
try:
return self.stack2[len(stack2)-1]
except:
print("Cannot peek into stack 2")
def is_empty(self):
if len(self.stack2) == 0:
return True
else:
return False
def display(self):
print(self.stack2)
class DoubleStackQueue(Stack2):
def __init__(self):
super(DoubleStackQueue, self).__init__()
pass
def enqueue(self, item):
self.item = item
super(DoubleStackQueue, self).push(self.item)
Stack1.push(self.item)
dsq = DoubleStackQueue()
dsq.enqueue(2)
Here, I am trying to push an item to stack1 by accessing the push() method of class Stack1. However, I am getting the below error :-
E:\>python dsq.py
Traceback (most recent call last):
File "dsq.py", line 78, in <module>
dsq.enqueue(2)
File "dsq.py", line 75, in enqueue
Stack1.push(self.item)
TypeError: push() missing 1 required positional argument: 'item'
Could you please help me out ?
When you call an instance method directly from the class, as you are doing by calling Stack1.push, you need to explicitly provide the self parameter:
Stack1.push(self, self.item)
In your call Stack1.push(self.item) the self.item is passed as the self parameter and the interpreter raises an error because it is missing the other required positional argument item.
Alternatively use super:
super(Stack2, self).push(self.item)
This said:
I believe your code is quite messy. I'm pretty sure Stack2.push method should be responsible for calling Stack1.push, so that DoubleEndedQueue need not perform a double call.
You can replace super(DoubleEndedQueue, self).push(self.item) with just self.push.item... since DoubleEndedQueue doesn't define a push method the superclass Stack2 will be checked automatically.

Mirrorring a queue in python

I need to mirror a queue using a function called mirror
I have made the code for the queue class, but i dont know how to create a mirror of it. It needs to print out the original queue and then the same queue reversed
Any help would be appreciated
My Code:
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 is_empty(self):
return not self.items
def size(self):
return len(self.items)
class Stack:
def __init__(self):
self.items = []
def is_empty(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)
def mirror(n):
pass
This will work. Your queue is composed of a list, so you can use slice syntax on the list to get a reversed version of the queue.
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
def __str__(self):
'''Allow print to be called on the queue object itself'''
return str(self.items)
def __getitem__(self, i):
'''Allow the queue object to be indexable directly'''
return self.items[i]
def mirror(q):
return q[::-1]
q = Queue()
for i in range(10):
q.enqueue(i)
print q
print mirror(q)
Note: A queue appends to the end, not the start. That's the behaviour of a stack.
Maybe you give this one a try: How can I reverse a list in python
You can create a new queue using the reversed self.items list in a member function mirror.
q = ArrayQueue()
def mirror(q):
copy = ArrayQueue()
stack = ArrayStack()
while not q.is_empty():
stack.push(q.first())
copy.enqueue(q.dequeue())
while not stack.is_empty():
copy.enqueue(stack.pop())
for i in range(len(copy)):
print(copy.dequeue(),end=" ")

Categories

Resources