jmportilla / Python-for-Algorithms--Data-Structures--and-Interviews

Files for Udemy Course on Algorithms and Data Structures

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return error instead of raise error?

the-zebulan opened this issue · comments

I'm not exactly sure this is an issue but I'm going through your Udemy course right now (great course by the way!) and I was wondering about this part.

Dynamic Array Exercise.ipynb

def __getitem__(self, k):
    """
    Return element at index k
    """
    if not 0 <= k < self.n:
        return IndexError('K is out of bounds!') # Check it k index is in bounds of array

    return self.A[k] #Retrieve from array at index k

Is there a particular reason why you use return IndexError instead of raise IndexError? I've searched a bit on the internet but cannot find a similar example. I'm only familiar with using raise IndexError and this is the first time I've seen an error returned like that.

Thanks!

EDIT:

Just noticed a potential typo in your code as I was re-reading my comment.

# Check it k index
        ^^
#       if ?

i'm using this code to see if it's doubling but it's not doing that

import sys n=10 for i in range(n): # Number of elements a = len(arr) # Actual Size in Bytes b = sys.getsizeof(arr) print 'Length: {0:3d}; Size in bytes: {1:4d} '.format(a,b) arr.append(n)

Length: 2; Size in bytes: 64 Length: 3; Size in bytes: 64 Length: 4; Size in bytes: 64 Length: 5; Size in bytes: 64 Length: 6; Size in bytes: 64 Length: 7; Size in bytes: 64 Length: 8; Size in bytes: 64 Length: 9; Size in bytes: 64 Length: 10; Size in bytes: 64

@cowboyuniverse

sys.getsizeof(arr) calculates the size of the DynamicArray() object itself - not the array size. The solution is to create a sizeof function which returns the actual size of the array (in bytes).

def __sizeof__(self):
        """
        Return the size of the object
        """
        
        return self.capacity * ctypes.sizeof(ctypes.py_object)

https://docs.python.org/3/library/sys.html#sys.getsizeof