Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class method doesn't return value

Tags:

python

methods

I'm working through the MTIx 6.00.1x Intro to Computer Science class, and am having trouble creating class methods. Specifically, the 'remove' function within my 'Queue' class does not return the value as I'd expect.

Here's context on the request:

For this exercise, you will be coding your very first class, a Queue class. In your Queue class, you will need three methods:

init: initialize your Queue (think: how will you store the queue's elements? You'll need to initialize an appropriate object attribute in this method)

insert: inserts one element in your Queue

remove: removes (or 'pops') one element from your Queue and returns it. If the queue is empty, raises a ValueError.

I've written the following code with a 'remove' method, but though the method's behavior correctly alters the array, it doesn't return the 'popped' value:

class Queue(object):

    def __init__(self):
        self.vals = []

    def insert(self, value):
        self.vals.append(value)

    def remove(self):
        try:
            self.vals.pop(0)
        except:
            raise ValueError()

Any help would be greatly appreciated!

like image 410
joanx737 Avatar asked May 02 '26 18:05

joanx737


1 Answers

Well, returning is rather easy in Python, so just do this:

def remove(self):
    try:
        return self.vals.pop(0)
    except:
        raise ValueError()

Luckily, pop() already removes and returns the selected element at the same time.

like image 95
TidB Avatar answered May 05 '26 07:05

TidB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!