0

I defined a method, like so:

class MyDatastructure(object):
    # init method here

    def appending(self, elem):
        self.data.append(elem)
        if self.count >= self.size:
            print "popping " + str(self.data[0])
            print "inserting " + str(elem)
            self.data.pop(0)
        elif self.count < self.size:
            self.count += 1
            print "count after end of method " + str(self.count)

I tested it out, and it worked as supposed to.

Underneath this definition, I wanted to process some user input and use this method. However, it doesn't enter the if case anymore! Any idea why?

# in the same file
def process_input():
    while True:
        # getting user input
        x = raw_input()
        ds = MyDatastructure(x)  # creating data structure of size, which was taken from user input, count initially 0
        ds.appending(1)
        ds.appending(2)
        ds.appending(3) 
        # Still appending and NOT popping, even though the if in appending doesn't allow it!   
        # This functionality works if I test it without user input!
MJP
  • 5,327
  • 6
  • 18
  • 18
  • How are you getting the user input? – Michael0x2a Jan 05 '14 at 20:41
  • through raw_input, see my edited question. – MJP Jan 05 '14 at 20:44
  • It's silly to follow up `if somecondition` with an `elif` that has the exact opposite condition. It does the same thing as `else`, but it *looks* like something weird is going on. – hobbs Jan 05 '14 at 20:50
  • I know this. I did it on purpose for testing because I couldn't figure out why it didn't enter if (initially I had if and else). – MJP Jan 05 '14 at 20:58

1 Answers1

2

The problem is with this line:

x = raw_input()

Calling raw_input will return a string. If I type in the number 3, that means that the data structure will assign the string "3" to the size.

Attempting to compare a string to a number is considered undefined behavior, and will do weird things -- see this StackOverflow answer. Note that Python 3 fixes this piece of weirdness -- attempting to compare a string to an int will cause a TypeError exception to occur.

Instead, you want to convert it into an int so you can do your size comparison properly.

x = int(raw_input())
Community
  • 1
  • 1
Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
  • Thanks :)! That worked. Still need to get used to typing in Python. Thanks for the informative answer! – MJP Jan 05 '14 at 20:56