Python Stack without using Pop function -


i learning python , have assignment better understanding of "class" , using "stack."

the requirements follows:

-define class implements stack numerical values.

-cannot use built-in pop function

-function push should check if value numerical

-function print_stack should print values in stack, recent (on top) first

-function isempty should return true if stack empty, false otherwise

here work far:

class stack():     def __init__(self):         self.items = []      def push(self, item):         self.items.append(item)      def isempty(self):         return (self.items == [])  #can use return not self think?      def print_stack(self):         print self.items   

this first class in programming i'm sorry if understanding poor. i'm not looking outright write me. want understand how go , receive pointers on need lacking in understanding if obvious.

my questions follows:

1) how can test if pushing numerical value? on first thought, use try/except?

2) best way go creating pop function without using 1 that's built in? giving me hard time. understanding need write retrieve last item list , return it.

3) test code this?

test = stack() test.push(1) test.print_stack() test.pop()  #whenever learn how make pop function test.isempty 

how can test if pushing numerical value? on first thought, use try/except?

you don't need test it. convert int or whatever datatype working on @ point. e.g. if working int

def push(self, item):     self.items.append(int(item)) 

if working float

def push(self, item):     self.items.append(float(item)) 

if working string

def push(self, item):     self.items.append(str(item)) 


what best way go creating pop function without using 1 that's built in? giving me hard time. understanding need write retrieve last item list , return it.

there multiple ways,

  1. use del

    def pop(self):     n = self.items[0]     del self.items[0]     return n 
  2. use slicing

    def pop(self):     n = self.items[0]     self.items = self.items[1:]     return n 

    note return subset of original not modify it.

  3. use popleft()

    def pop(self):     return self.items.popleft() 

one suggestion can use len() check length of list , use check whether stack empty or not,

def isempty(self):     return (len(self.items) == 0) 

note: before popping use isempty() function check if stack empty.


to test code ?

just try executing every function, if think there problem print stack after every operation. see how values getting updated in stack.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -