5 Replies - 356 Views - Last Post: 13 February 2013 - 10:09 PM Rate Topic: -----

#1 medaa  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 24-October 12

class error

Posted 11 February 2013 - 10:45 AM

class BoundedQueue:
    
    # Constructor, which creates a new empty queue, with user-specified capacity:
    def __init__(self, capacity):
        self.__items=[]
                
    # Adds a new item to the back of the queue, and returns nothing:
    def enqueue(self, item):
        self.__items.append(item)
    
    # Removes and returns the front-most item in the queue.  
    # Returns nothing if the queue is empty.
    def dequeue(self):
        if len(self.__items)!=0:
            return self.__items.pop(0)        
        
    # Returns the front-most item in the queue, and DOES NOT change the queue.  
    def peek(self):
        if len(self.__items)==0:
            return None
        return self.__items[0]        
    
    # Returns True if the queue is empty, and False otherwise:
    def is_empty(self):
        return len(self.__items) == 0
      
    # Returns True if the queue is full, and False otherwise:
    def is_full(self):
        return True
    
    # Returns the number of items in the queue:
    def size(self):
        return len(self.__items)
        
    # Returns the capacity of the queue:
    def capacity(self):
        self.__item=[]
    
    # Removes all items from the queue, and sets the size to 0.
    # clear() should not change the capacity
    def clear(self):
        self.__items=[]
        
    # Returns a string representation of the queue:
    def __str__(self):
        return("Memebers:{0} \nSize:{1}".format(self.__items,len(self.__items)))

#use this function to test your Bounded Queue implementation    

def test():
    is_pass = True

    try:
        string_queue = BoundedQueue('wrong type')
    except Exception as e:
        is_pass = True
    else:
        is_pass = False
    assert is_pass == True, "fail the test"
    
    try:
        string_queue = BoundedQueue(-1)
    except Exception as e:
        is_pass = True
    else:
        is_pass = False  
    assert is_pass == True, "fail the test" 
        
    string_queue = BoundedQueue(3)
    
    is_pass = (string_queue.size() == 0)
    assert is_pass == True, "fail the test"
    
    is_pass = (string_queue.capacity() == 3)
    assert is_pass == True, "fail the test" 
    
    is_pass = (string_queue.is_empty())
    assert is_pass == True, "fail the test"
    
    string_queue.enqueue("Hello")
    string_queue.enqueue("World")
    
    is_pass = (string_queue.size() == 2)
    assert is_pass == True, "fail the test"
    
    is_pass = (string_queue.peek() == "Hello")
    assert is_pass == True, "fail the test"

    is_pass = (string_queue.capacity() == 3)
    assert is_pass == True, "fail the test"
    
    is_pass = (string_queue.peek() == "Hello" and string_queue.size() == 2)
    assert is_pass == True, "fail the test"

    
    string_queue.enqueue("python")
    
    is_pass = (string_queue.is_full())
    assert is_pass == True, "fail the test" 
    
    try:
        string_queue.enqueue("rules")
    except Exception as e:
        is_pass = True
    else:
        is_pass = False
    assert is_pass == True, "fail the test"
    
    string_queue.clear()
    
    is_pass = (string_queue.capacity() == 3)
    assert is_pass == True, "fail the test" 
    
    try:
        string_queue.dequeue()
    except Exception as e:
        is_pass = True
    else:
        is_pass = False
    assert is_pass == True, "fail the test" 
        
    try:
        string_queue.peek()
    except Exception as e:
        is_pass = True
    else:
        is_pass = False
    assert is_pass == True, "fail the test"
    
    int_queue = BoundedQueue(2000)
    for i in range(0, 1000):
        int_queue.enqueue(i)      
    correctOrder = True
    for i in range(0, 200):
        if int_queue.dequeue() != i:
            correctOrder = False
            
    is_pass = correctOrder
    assert is_pass == True, "fail the test" 
    
    is_pass = (int_queue.size() == 800)
    assert is_pass == True, "fail the test" 
 
    is_pass = (int_queue.capacity() == 2000)
    assert is_pass == True, "fail the test"    

    is_pass = (int_queue.peek() == 200)
    assert is_pass == True, "fail the test"
    
    if is_pass == True:
        print ("=========== cong, your implementation passes the test ============")


#let's test it
if __name__ == '__main__':
    test()


So I have everything except: def __init__(self, capacity):, def is_full(self):, def capacity(self):
For def__init__(self, capacity) I need to raise an exception if capacity is negative and if its not a integer,
Ive tried a bunch of methods but there all wrong, the program keeps crashing on line 59, the def test(): is given to test my class so the problem is from the class, can i get some help.

Is This A Good Question/Topic? 0
  • +

Replies To: class error

#2 TheKirk  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 58
  • Joined: 10-February 13

Re: class error

Posted 11 February 2013 - 10:57 AM

The error I'm getting when I run your code:

Traceback (most recent call last):
  File "test.py", line 156, in <module>
    test()
  File "test.py", line 59, in test
    assert is_pass == True, "fail the test"
Assertionerror: fail the test


My guess it that 'assert' throws an error, I'm not an Python expert but it seems to do just that. The assert keyword is there to help you find bugs. It throws a runtime error so you can sport your bugs more easily. It's not to throw an error to the user that his input was invalid but to help developers find bugs.

Read:

http://wiki.python.o...ionsEffectively

Again, i'm not a python exper.
Was This Post Helpful? 0
  • +
  • -

#3 woooee  Icon User is offline

  • D.I.C Head

Reputation: 21
  • View blog
  • Posts: 78
  • Joined: 21-November 12

Re: class error

Posted 11 February 2013 - 06:16 PM

Exceptions are a topic all there own. You can start with Doug Hellmann's examples. The following code tries to convert to an integer, and if not successful the ValueError exception is raised. If successful it then tests for greater than zero, and will raise ValueError again if that test fails. Note that the following code is about as simple as it gets.
def print_success():
    print "--> conversion success"

for num in [1, -2, 'a', 3, 0]:
    print num,
    try:
        num_int = int(num)
        if num_int < 1:
            raise ValueError()
        print_success()
    except ValueError:
        print "     Could not convert data to a positive integer."
    except:
        print "Unexpected error:", sys.exc_info()[0]
    print 

"""   results
1 --> conversion success

-2      Could not convert data to a positive integer.

a      Could not convert data to a positive integer.

3 --> conversion success

0      Could not convert data to a positive integer.
"""

This post has been edited by woooee: 11 February 2013 - 06:19 PM

Was This Post Helpful? 0
  • +
  • -

#4 Mekire  Icon User is offline

  • D.I.C Head

Reputation: 116
  • View blog
  • Posts: 212
  • Joined: 11-January 13

Re: class error

Posted 12 February 2013 - 03:46 AM

In order to pass the given test you need to raise an exception every time the user does something that isn't allowed.
The assertions are checking if, after a given test, the expected value is found. If the desired result is found, no exception is raised. If not an Assertionerror is raised.

The way your instructor has written this you will need to raise exceptions when the user tries to queue to a full queue; tries to dequeue from an empty queue; tries to peek at an empty queue etc. etc.

I personally agree it is a pretty bad assignment and your instructor should have at least commented the test section so that you understood what you were testing for each time.

I managed to get the test to pass, but it was indeed annoying.
Here is the __init__ function I used for you to look at as an example:
def __init__(self,capacity):
        self.items = []
        self.sz  = 0
        if isinstance(capacity,int) and capacity > 0:
            self.cap = capacity
        else:
            raise TypeError

Just keep in mind that any time the user does something prohibited, you must raise an exception.
Your crash on line 59 for example occurs when the user attempts to create a queue with a capacity that is a string rather than an integer greater than 0. If an exception is raised when the user does this then the test passes. If no exception is raised the test fails.

Let's see an updated attempt and I will help further,
-Mek
Was This Post Helpful? 0
  • +
  • -

#5 medaa  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 24-October 12

Re: class error

Posted 13 February 2013 - 07:01 PM

So for every method I have to raise an expectation?
Was This Post Helpful? 0
  • +
  • -

#6 Mekire  Icon User is offline

  • D.I.C Head

Reputation: 116
  • View blog
  • Posts: 212
  • Joined: 11-January 13

Re: class error

Posted 13 February 2013 - 10:09 PM

When something prohibited (by the rules of your class) occurs, either you must explicitly raise an exception, or an exception must automatically be raised as a result of your code.

For example enqueue will not raise an exception automatically if you queue beyond your capacity, so you must tell it to raise one:
def enqueue(self,item):
    if len(self.items) < self.cap:
        self.items.append(item)
    else:
        raise IndexError

On the other hand; if you try to dequeue from an already empty queue, an exception will be raised regardless. In this case, this is sufficient:
def dequeue(self):
    return self.items.pop(0)

In the enqueue function when we queue past capacity we tell it to raise an exception (I chose IndexError because it makes the most sense, but it doesn't matter). In the case of dequeue, trying to pop from an empty list will already raise an exception (which in this case is exactly what you want), so there is no need to raise one.

-Mek
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1