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.
Related
I'd like to cache an object in __new__ method so that it can load the cache when a new object is constructed, but now the following code will got an exception:
RecursionError: maximum recursion depth exceeded while calling a Python object
I have no idea about how to break the recursion
import pickle
class Cache:
def __init__(self):
self.d = {}
def __setitem__(self, obj, val):
self.d[obj] = pickle.dumps(val)
def __getitem__(self, obj):
return pickle.loads(self.d[obj])
class Car:
cache = Cache()
def __reduce__(self):
return (self.__class__, (self.name,))
def __new__(cls, name):
try:
return cls.cache[name]
except KeyError:
return cls.new(name)
#classmethod
def new(cls, name):
car = object.__new__(cls)
car.init(name)
cls.cache[name] = car
return car
def init(self, name):
self.name = name
def __repr__(self):
return self.name
a = Car('audi')
b = Car('audi')
Have a try. This may fix this, but it may not be the proper solution. If anyone have any better idea, feel free to leave comments.
Just remove the __reduce__ method.
Then implement __getnewargs__ and __getnewargs_ex__
import pickle
class Cache:
def __init__(self):
self.d = {}
def __setitem__(self, obj, val):
self.d[obj] = pickle.dumps(val)
def __getitem__(self, obj):
return pickle.loads(self.d[obj])
def __contains__(self, x):
return x in self.d
class Car:
cache = Cache()
def __new__(cls, name, extra=None, _FORCE_CREATE=False):
if _FORCE_CREATE or name not in cls.cache:
car = object.__new__(cls)
car.init(name)
car.extra = extra
cls.cache[name] = car
return car
else:
return cls.cache[name]
def init(self, name):
self.name = name
def __repr__(self):
return self.name
def __getnewargs__(self):
return (self.name, None, True)
def __getnewargs_ex__(self):
# override __getnewargs_ex__ and __getnewargs__ to provide args for __new__
return (self.name, ), {"_FORCE_CREATE": True}
a = Car('audi', extra="extra_attr")
b = Car('audi')
print(id(a), a.extra) # 1921399938016 extra_attr
print(id(b), b.extra) # 1921399937728 extra_attr
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.
I'm reading a book on data structures and algorithms and understand the overall goal of the code but for top() and pop() there are strange member variables. Is this some sort of python abstraction that I am running into (ex. self._head._element) or a feature of not using pythons dictionary variable assignment?
'''
class LinkedStack:
class _Node:
__slots__ = '_element','_next' #treats elements not like a dictionary
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
self._head = None
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
def push(self, e):
self._head = self._Node(e, self._head)
self._size += 1
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
else:
return self._head._element
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
answer = self._head._element
self._head = self._head._next
self._size -=1
return answer
'''
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=" ")
I want to create a class myCalc that has a constructor, with get and set methods and uses a property. I understand the get and set methods but am having trouble with putting all of the pieces together so it performs what I want it to do. What I have so far is this:
class myCalc(object):
def __init__(self):
self._ =name
def (self):
"""Get the answer doubled."""
return self._plus
def (self):
"""Get the answer squared."""
return self._times
I'd like to get as far as having the program respond with properties that double and square the number in the object. Any suggestions would be helpful.
A property object has getter, setter, and deleter methods
You should use decorators as follows:
class C(object):
def __init__(self):
self._x = None
#property
def x(self):
"""I'm the 'x' property."""
return self._x
#x.setter
def x(self, value):
self._x = value
#x.deleter
def x(self):
del self._x
If you want it readonly, just use #property and remove the two others
A simple object that has doubled and squared properties
class myCalc(object):
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
def dbler(self):
return self.value*2
doubled = property(dbler)
squared = property(lambda self: self.value**2)
# equivalent with the decorator
#property
def cubed(self):
return self.value**3
if __name__ == '__main__':
x = myCalc(10)
print x # 10
print x.doubled # 20
print x.squared # 100
print x.cubed # 1000
Adapted from http://docs.python.org/2/howto/descriptor.html#properties
class myCalc(object):
def_init_(self, value)
self.value=value
def_init_(self, name)
print "Welcome to myCalc!"
self._name=name
def get_name(self):
return self._name
def set_name(self, new_name):
if new_name=="":
print "You mut enter a name."
else:
self._name=new_name
print "The name has been changed."
def_str_(self)
return str(self.value)
def dbler(self):
return self.value*2
doubled=property(dbler)
squared=property(lambda self: self.value**2)
name=property(get_name, set_name)
def talk(self):
print "\nWelcome, this is," self.name
if name=='main':
x= myCalc(5)
print x
print x.doubled
print x.squared
mainline
calc=myMath("Calculator")
calc.talk()
print "\nmyCalc's name is:",
print calc.name
print "\nChanging myCalc's name."
calc.name=""
calc.talk()
raw_input("\n\nPress the enter key to exit."
Here is what I am looking to do, however I keep coming across errors. I want to be able to change the object name AND number.