Reputation: 57
I made a simple stack program but I am able to enter more elements than the size given to stack by user input. The if len(self.stk)==size
statement doesn't seem to work and I can't understand why.
This is my code:
class stack():
def __init__(self,size):
self.stk=[]
self.size = size
def push(self,item):
if len(self.stk)==self.size:
print"OVERFLOW!"
else:
self.stk.append(item)
print "Len of stack is ",len(self.stk)
print "Size is ",self.size
def pop(self):
if self.isempty()==True:
print "UNDERFLOW"
else:
del self.stk[-1]
def isempty(self):
if self.stk==[]:
return True
else:
return False
def display(self):
print "\nNow going to show you the stack: \n "
for i in range(len(self.stk)-1,0,-1):
print self.stk[i]
size = raw_input("Enter size of stack you want: ")
stak = stack(size)
while True:
choice = int(raw_input("\nEnter \n 1.To push an item \n 2.Pop an item \n 3. Display Stack \n 4.Quit: "))
if choice == 1:
elem = raw_input("Enter the element you want to enter: ")
stak.push(elem)
if choice == 2:
stak.pop()
if choice == 3:
stak.display()
if choice==4:
break
Upvotes: 0
Views: 74
Reputation: 7952
You need to typecast the input to a number
size = int(raw_input("Enter size of stack you want: "))
Alternatively, since you're working in Python2.7:
size = input("Enter size of stack you want: ")
Would work, as it will evaluate what they give it and (if given a whole number) will return an integer.
In the future, one thing I may suggest:
Add the following function and you can then inspect all of your variables at any point:
def debug(*args):
print('Variable debugger output:')
for arg in args:
if arg in ["__builtins__", "inspect", "debug"]:
continue # skip these variables
try:
var = eval(arg)
print('{0}: {1} {2}'.format(arg, type(var), var))
# Handles variables not passed as strings
except (TypeError, NameError):
print('{0}: {1}'.format(type(arg), arg))
with
debug(*dir()) # All variables in scope
or
debug('size', 'self.size') # Specific variables - Note it accepts both a list
debug(size, self.size) # of strings or a list of variables
which will give you something like:
debug: <type 'function'> <function debug at 0x7fa046a4f938>
in2: <type 'int'> 5
normin: <type 'int'> 23 # normal input
rawin: <type 'str'> 23 # raw input
sys: <type 'module'> <module 'sys' (built-in)>
test: <type 'str'> Hello
testfloat: <type 'float'> 5.234
Note: debug won't show itself if you use the code above... this shows what a function looks like from the debugger.
Upvotes: 3