python how to inherit parent stack - python

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.

Related

Python class does not have value

I am a Javascript engineer and am switching into a JS/Python role. Working on some easy leetcodes to get some quick Python practice.
I'm looking to create a LinkedList here and perhaps I am coming at it from a JS mindset?
Error:
AttributeError: type object 'LinkedListNode' has no attribute 'value'
utils.py
# LinkedList Methods
def createLinkedList(arr):
head = createLinkedListNode(None, arr.pop(0))
def populateList(arr, prevNode):
if arr:
node = createLinkedListNode(None, arr.pop(0))
prevNode.next = node
if arr:
populateList(arr, node)
populateList(arr, head)
return head
def createLinkedListNode(next, value):
class LinkedListNode:
def __init__(self):
self.next = next
self.value = value
return LinkedListNode
deleteNode.py
from python.utils import createLinkedList, linkedListToArray
useCase1 = [4, 5, 1, 9]
linkedList = createLinkedList(useCase1)
^ linkedList.value doesn't exist?
Some misunderstandings with python classes:
The class LinkedListNode should not defined in function.
Return LinkedListNode is actually returning the class itself, but not the Instance. To return the instance, you have to call the class. return LinkedListNode()
Using next as instance variable is not ideal. next is an iteration function in python, so when you set self.next = next, you are actually assigning the function to self.next
If you want to set a variable, for example self.next_value = next_value, you should put next_value as a parameter of __init__ function, like def __init__(self, next_value)
Here is a simple demo of Linked List:
class LinkedList:
def __init__(self, value):
self.value = value
self.next_value = None
def __iter__(self):
yield self.value
if self.next_value is not None:
yield from self.next_value
# else raise StopIteration
def __getitem__(self, index):
if index == 0:
return self.value
else:
return self.next_value[index-1]
# recursively get the next value
def __str__(self):
return str(self.value) + ' -> ' + str(self.next_value)
def __len__(self):
if self.next_value is None:
return 1
else:
return 1 + len(self.next_value)
# recursively get the length
def append(self, value):
if self.next_value is None:
self.next_value = LinkedList(value, self)
else:
self.next_value.append(value)
a = LinkedList(2)
a.append(1)
a.append(3)
for num in a:
print(num, end=", ")
print()
print(a[1])
print(a)
print(len(a))
Output:
2, 1, 3,
1
2 -> 1 -> 3 -> None
3
createLinkedListNode() returns the LinkedListNode class itself, not an instance of the class.
Why are you defining classes and functions inside of other functions? That's an odd way of doing things.

'function' object has no attribute 'push'

import Queue_PlistLR as queueList
class Stack_2Queues():
def __init__(self, name, salary):
self.items = []
self.name = name
self.salary = salary
def isEmpty(self):
return len(self.items) == 0
def push(self, e):
self._data.append(e)
def pop(self):
if self.is_empty:
raiseEmpty("Stack is empty")
return self._data.pop()
def size(self):
return len(self.items)
def to_String(self):
str_i = ""
for e in self.items:
str_i+=str(e)+" "
return str_i.strip()
def length(self):
return len()
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if self.isEmpty():
raise Empty('Queue is empty')
return self.items.pop(0)
def employeeName(self):
print("The employee is: ", self.name)
def employeeSalary(self):
print("Employees salary is", self.salary)
s1 = Stack_2Queues(["Ash", "Jen", "Mike", "Zach"], [45000, 32000, 74000, 960000])
s1.employeeName()
s1.employeeSalary()
s1.employeeName.push("Earl")
s1.employeeSalary.push(55000)
I am trying to push new values to the queues employeeName and employeeSalary()
However I am faced with this error. What am I doing wrong?
s1.employeeName.push("Earl")
s1.employeeSalary.push(55000)
This is calls of push on methods. What is the idea? You have push/pop methods on your class, start with calling s1.push
Btw, you should probably look into deque
'function' object has no attribute 'push'
...
What am I doing wrong?
employeeName and employeeSalary are not queues, the are instance methods (functions) of your class. They do not have a (callable) push attribute. They do not contain anything, they do something, so you cannot add to them.

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.

creating a class in python - error

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.

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