Question 5 & 4 of assignment 2

i cant figure out the problem in my code, as far Q4 i get all the output correct but the output after executing Q5 is False. Here’s the code of Q4 and Q5 both.

def get_valid_index(data_list, key):
# Start with the index returned by get_index
idx = get_index(data_list, key)

while True:
    # Get the key-value pair stored at idx
    kv = data_list[idx]
    
    # If it is None, return the index
    if kv is None:
        return idx
    
    # If the stored key matches the given key, return the index
    k, v = kv
    if k == data_list[idx]:
        return idx
    
    # Move to the next index
    idx += 1
    
    # Go back to the start if you have reached the end of the array
    if idx == len(data_list):
        idx = 0

Q5

class ProbingHashTable:
def init(self, max_size=MAX_HASH_TABLE_SIZE):
# 1. Create a list of size max_size with all values None
self.data_list = [None] * max_size

def insert(self, key, value):
    # 1. Find the index for the key using get_valid_index
    idx = get_valid_index(self.data_list, key)
    
    # 2. Store the key-value pair at the right index
    self.data_list[idx] = key, value


def find(self, key):
    # 1. Find the index for the key using get_valid_index
    idx = get_valid_index(self.data_list, key)
    
    # 2. Retrieve the data stored at the index
    kv = self.data_list[idx]
    
    # 3. Return the value if found, else return None
    if kv != None:
        return kv[1]
    else:
        return None


def update(self, key, value):
    # 1. Find the index for the key using get_valid_index
    idx = get_valid_index(self.data_list, key)
    
    # 2. Store the new key-value pair at the right index
    self.data_list[idx] = key, value


def list_all(self):
    # 1. Extract the key from each key-value pair 
    return [kv[0] for kv in self.data_list if kv is not None]

In the code for Q4…
in line where you are comparing if k == data_list[idx] is wrong…
Instead you have to compare k with the given key
because we need to find the valid index for key and moreover, k == data_list[idx] will always give True because k was extracted from kv which was extracted from data_list

1 Like

In question 4 all my code is same as above and I have also compared k with key i.e k== key as you said but the code isn’t running it shows the error “cannot unpack non-iterable NoneType object”
could you help me plz