how to print elements of a stack in python 3 -
i have print elements in stack using classes , all:
class stack: def __init__(self): self.stack = [] def push(self,element): self.stack.append(element) def pop(self): return self.stack.pop() def st(n): s = stack() in range(n,0,-1): s.push(i) #this updated version want print outside of loop , #it gives me error : __main__.stack instance @ 0x7fe40d261710> print s if __name__ == '__main__': st(4)
for reason instead of printing [4,3,2,1] print none
stask class using built-ins
using lists stack https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks
the list methods make easy use list stack, last element added first element retrieved (“last-in, first-out”). add item top of stack, use append(). retrieve item top of stack, use pop() without explicit index
if have provide custom interface adding elements in stack can add single method this:
class stack(list): def push(self, *args, **kwargs): self.append(*args, **kwargs)
printing objects
how print
function behave?
lets @ documentation print
function https://docs.python.org/3/library/functions.html#print
all non-keyword arguments converted strings str() , written stream, separated sep , followed end.
what str()
function does?
if neither encoding nor errors given, str(object) returns
object.__str__()
, “informal” or nicely printable string representation of object. string objects, string itself. if object not have__str__()
method, str() falls returningrepr(object)
.
this means stack
have support __str__()
method, , if has no such __repr__()
used.
look @ repr(object)
docs if didn't believe words https://docs.python.org/3/library/functions.html#repr
a class can control function returns instances defining repr() method.
also read answers, describe thoughts in different manner:
- difference between __str__ , __repr__ in python explain practical use cases
- difference between __str__ , __repr__ in python explain meaning of each method
summary
class stack(list): """ implaments stack interface access data inheriting buil-in list object. note: parent methods accessable in stack instance. """ def push(self, *args, **kwargs): """ delegate behaviour parrent class. """ self.append(*args, **kwargs) def __str__(self): """ because of using list parent class stack, our last element first stack, according fifo principle. so, if use parent's implementation of str(), reversed order of elements. """ #: can reverse elements , use supper `__str__` method, or #: implement it's behavior yourself. #: choose add 'stack' in begging in order differ list , #: stack instances. return 'stack [{}]'.format(', '.join(reversed(self))) def example_of_usage(): #: here using parent's list initialization functionality init #: stack iterable (in our case - list). s = stack(['last', 'first']) #: output> stack ['fist', 'last'] print(s) s.push('very first') #: output> stack ['very first', 'fist', 'last'] print(s)
Comments
Post a Comment