Derek Xie - 10 months ago 41

Python Question

For the following program, in the addEntry(self, dictKey, dictVal) function, I don't understand why the following line of code doesn't generate indexing error:

`if hashBucket[i][0] == dictKey`

`self.buckets`

`self.buckets = [[],[]...[]]`

When addEntry is executed the first time,

`hashBucket`

`hashBucket[i][0]`

Here is the program

`class intDict(object):`

"""A dictionary with integer keys"""

def __init__(self, numBuckets):

"""Create an empty dictionary"""

self.buckets = []

self.numBuckets = numBuckets

for i in range(numBuckets):

self.buckets.append([])

def addEntry(self, dictKey, dictVal):

"""Assumes dictKey an int. Adds an entry"""

hashBucket = self.buckets[dictKey%self.numBuckets]

for i in range(len(hashBucket)):

if hashBucket[i][0] == dictKey:

hashBucket[i] = (dictKey, dictVal)

return

hashBucket.append((dictKey, dictVal))

def getValue(self, dictKey):

"""Assumes dictKey an int. Returns entry associated with the key dictKey"""

hashBucket = self.buckets[dictKey%self.numBumBuckets]

for e in hashBucket:

if e[0] == dictKay:

return e[1]

return None

def __str__(self):

result = '{'

for b in self.buckets:

for e in b:

result = result + str(e[0]) + ":" + str(e[1]) + ','

return result[:-1] + '}' # result[:-1] omits the last coma

Answer Source

Since `hashBucket`

is an empty list at first, `for i in range(len(hashBucket)):`

is essentially `for i in range(0):`

, meaning it never gets to the conditional `if hashBucket[i][0] == dictKey`

on the first call to `addEntry`

.