I have stack code:
class Stack:
def __init__(self):
self.__data = []
def empty(self):
return len(self.__data) == 0
def size(self):
return len(self.__data)
def push(self, x):
self.__data.append(x)
def pop(self):
return self.__data.pop()
and adds numbers 1, 2:
stack = Stack()
stack.push(1)
stack.push(2)
and I don't know how to print __data list?
so that it shows 1,2 in the list?
[1,2]
As __data is a private attribute of stack object, it cannot be accessed outside the class. Instead define an instance method to print the stack list as shown below.
class Stack:
def print_stack(self):
print(self.__data)
Now if you call print_stack() on an instance. It will print the __data list.
You can use __str__ method to print the values using print() or __repr__ for direct representation.
class Stack:
def __init__(self):
self.data = []
def empty(self):
return len(self.data) == 0
def size(self):
return len(self.data)
def push(self, x):
self.data.append(x)
def pop(self):
return self.data.pop()
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self.data)
>>> stack = Stack()
>>> stack.push(1)
>>> stack.push(2)
>>> print(stack) ## using __str__
# [1, 2]
>>> stack ## using __repr__
# [1, 2]
I have one more question. My code:
class Stack:
def __init__(self):
self.data = []
def empty(self):
return len(self.data) == 0
def size(self):
return len(self.data)
def push(self, x):
self.data.append(x)
def pop(self):
if len(self.data) == 0:
print("underflow")
else:
return self.data.pop()
def __str__(self):
return str(self.data)
stack = Stack()
stack.push(1)
stack.push(2)
print(stack)
I print the list as I wanted:
[1,2]
Now i wonder if i can work on this list? That is, as always on the lists:
In this case:
list = stack
list[0]
1
Can you recommend some simple courses where do Class is explained? I feel confused and my questions seem simple...
Related
This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 3 years ago.
can anybody explain why it is showing me and how to print it?
what am I doing wrong and how to print this object reference?
i have also tried printing new_list(inside sort() ) but still the same
I am printing list then why it is not showing
I know some of the people asked before about related to this...but still I didn't get it.
class node(object):
def __init__(self, d, n=None):
self.data=d
self.next_node=n
def get_data(self):
return self.data
def set_data(self,d):
self.data=d
def get_next(self):
return self.next_node
def set_next(self, n):
self.next_node=n
def has_next(self):
if self.get_next() is not None:
return True
else:
False
class LinkedList(object):
def __init__(self, r=None):
self.root=r
self.size=0
def get_size(self):
return self.size
def add(self,d):
new_node = node(d, self.root)
self.root = new_node
self.size+=1
def sort(self):
if self.size>2:
newlist = []
this_node = self.root
newlist.append(this_node)
while this_node.has_next():
this_node = this_node.get_next()
newlist.append(this_node)
newlist = sorted(newlist ,key = lambda node: node.data,reverse=True)
newLinkedList = LinkedList()
for element in newlist:
newLinkedList.add(element)
return newLinkedList
return self
new_list=LinkedList()
new_list.add(10)
new_list.add(20)
new_list.add(30)
new_list.sort()
i expected that it will print list print a list
but it is showing <main.LinkedList object at 0x00E20BB0>
how to print this object ?
You are not printing out node values of the linked list instead you are printing out the return value of the sort() function which is an object of the class LinkedList.
If you want to print the linked list, you have to traverse the list and print out each node value individually.
Here is the recursive solution of how you can print a linked list.
def print_list(head):
if head != null:
print(head.val)
print_list(head.next)
You can call this method after calling the sort function
so I am trying to create a list of stack objects in Python. I have first created a class Stack that has simple methods that a Stack should have. I have then created another class called Stacks. I am trying to create a list of stacks. If a stack has more than 3 elements, it creates a new stack but I get an error when I try to display the elements. Could someone point out what I might be doing wrong here please?
class Stack:
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 size(self):
return len(self.items)
def printStack(self):
for item in reversed(self.items):
print (item)
class Stacks:
def __init__(self):
self.stacks = []
self.noOfStacks = 0
self.itemsOnStack = 0
def dev(self):
self.stacks.append(Stack())
# if len(self.stacks) != 0:
# self.noOfStacks += 1
def push(self, item):
if self.itemsOnStack > 3:
self.dev()
else:
self.itemsOnStack += 1
self.stacks[self.noOfStacks].push(item)
def pop(self, stackNo):
return self.stacks(noOfStacks).pop()
def size(self):
return len(self.stacks)
def printtack(self, index):
print (len(self.stacks(index)))
self.stacks(index).printStack()
stacky = Stacks()
stacky.dev()
stacky.push(3)
stacky.printtack(0)
Indexing lists in Python works by [] not (). Try
def printtack(self, index):
self.stacks[index].printStack()
One thing to note as kshikama said indexing should be done using [] not (),the other problem is using the len() method in the stack class u most override the __len__() method or as u have given use the size() method
class Stack:
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 size(self):
return len(self.items)
def printStack(self):
for item in reversed(self.items):
print (item)
class Stacks:
def __init__(self):
self.stacks = []
self.noOfStacks = 0
self.itemsOnStack = 0
def dev(self):
self.stacks.append(Stack())
#if len(self.stacks) != 0:
#self.noOfStacks += 1
def push(self, item):
if self.itemsOnStack > 3:
self.dev()
else:
self.itemsOnStack += 1
self.stacks[self.noOfStacks].push(item)
def pop(self, stackNo):
return self.stacks(noOfStacks).pop()
def size(self):
return len(self.stacks)
def printtack(self, index):
print (self.stacks[index].size())
self.stacks[index].printStack()
stacky = Stacks()
stacky.dev()
stacky.push(3)
stacky.printtack(0)
OUTPUT
1
3
I'm doing some basic Python programming practice exercises and tried to implement a queue (using lists). Unfortunately, I'm getting behavior for my isempty() function that I don't understand. When running the code below, the last two lines give different answers: A yields False, while B yields True. Why doesn't A also yield False?
class Queue:
def __init__(self):
self.items = []
def push(self,item):
self.items.insert(0,item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
return self.size == 0
q = Queue()
q.push("a")
q.push("b")
print(q.pop())
print(q.isempty())
print(q.pop())
print(q.isempty()) # shouldn't this (A)...
print(q.size()==0) # ...and this (B) yield the same answer?
Just change your isempty() method to:
def isempty(self):
return self.size() == 0
Your implementation of Queue.isempty() is checking to see if the method size is equal to the integer 0, which will never be true.
class Queue:
def __init__(self):
self.items = []
def push(self,item):
self.items.insert(0,item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
return self.size == 0
q = Queue()
print(q.size)
Produces:
<bound method Queue.size of <__main__.Queue object at 0x02F4EA10>>
The easiest solution is to use Christopher Shroba's suggestion to modify your Queue.isempty() implementation to use the list's size method.
I'm working on a homework assignment where I shall implement selection sorting using forward iterators for both python lists and linked lists(single).
Here are some codes I have for iterators:
from abc import *
class ForwardIterator(metaclass=ABCMeta):
#abstractmethod
def getNext(self):
return
#abstractmethod
def getItem(self):
return
#abstractmethod
def getLoc(self):
return
#abstractmethod
def clone(self):
return
def __eq__(self, other):
return self.getLoc() == other.getLoc()
def __ne__(self, other):
return not (self == other)
def __next__(self):
if self.getLoc() == None:
raise StopIteration
else:
item = self.getItem()
self.getNext()
return item
class ForwardAssignableIterator(ForwardIterator):
#abstractmethod
def setItem(self, item):
"""Sets the item at the current position."""
return
class PythonListFAIterator(ForwardAssignableIterator):
def __init__(self, lst, startIndex):
self.lst = lst
self.curIndex = startIndex
def getNext(self):
self.curIndex += 1
def getItem(self):
if self.curIndex < len(self.lst):
return self.lst[self.curIndex]
else:
return None
def setItem(self, item):
if self.curIndex < len(self.lst):
self.lst[self.curIndex] = item
def getLoc(self):
if self.curIndex < len(self.lst):
return self.curIndex
else:
return None
def clone(self):
return PythonListFAIterator(self.lst, self.curIndex)
The LinkedListFAIterator is similar to PythonListFAIterator, plus getStartIterator, and __iter__ method.
I don't know how I can write codes to implement selection sort with one paraemter, a FAIterator (the forward iterator). Please help me. I know I shall find the minimum element and put it at the beginning of the list. I also know that I shall use the clone method to create multiple iterators to keep track of multiple locations at once. But I don't know how to write the code.
Please give me some hints.
Ok so im trying to input a word in a stack and I want to print all of them after I input a string. So I can only print them one at a time. I tried using a for loop outside but Stacks are apparently not iterable. So I iterating it inside the stack. It still is not working.
class Stack:
def __init__(self):
self.items = []
def push(self,items):
self.items.insert(0,items)
def pop(self):
for x in self.items:
print( self.items.pop(0))
def show(self):
print (self.items)
s = Stack()
s.show()
placed = input("enter")
item = s.pop()
print(item, "is on top", s)
Give your Stack class a __len__ method, this will make testing if the stack is empty easier:
class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def show(self):
print (self.items)
def __len__(self):
return len(self.items)
stack = Stack()
stack.push('World!')
stack.push('Hello')
while stack: # tests the length through __len__
print(stack.pop())
Note that I simply .append() to the end of the .items list, then later on .pop() (no arguments) again, removing from the end of the list.
To make your class an iterable type, you'd need to add at least an __iter__ method, optionally together with a .__next__() method:
class Stack:
# rest elided
def __iter__(self):
return self
def next(self):
try:
return self.items.pop()
except IndexError: # empty
raise StopIteration # signal iterator is done