Screen Link:
My Code:
def put(self, key, value):
# need self , calling a method inside a clase
index = self._get_index(key)
found_key = False
for entry in self.buckets[index]:
if entry.key == key:
entry.value = value
found_key = True
if not found_key:
self.buckets[index].append(Entry(key, value))
self.length += 1
What I expected to happen:
What actually happened:
Replace this line with the output/error
Why is key and value not self.key and self.value?
Any particular reason you think they should be self.key
and self.value
instead?
I am confused as to why in linked lists and dictionaries for example self.length is always referenced as self.length in the code but such variables as data, key and value are not . For example, data is initialized as self.data in def init but then is referenced as data ( not self.data) in the append function.
class Node:
def __init__(self,data):
self.data = data
self.prev = None
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def append(self,data):
new_node = Node(data)
if self.length == 0:
self.tail = new_node
self.head = new_node
else:
self.tail = new_node
new_node = self.tail
self.tail = new_node
self.length = self.length + 1
That’s dependent on which values you want to persist through your Class.
self.length
keeps track of the length of the Linked List, so you want its value to persist so that you can update it if you append anything to that Linked List. You could also have another method which prints the length of the Linked List for you, and in that case self.length
will be storing the current length and you can use that easily to print out the length.
That’s what I mean by having it persist through the Class - it continues to store the last value it had so that you can access that anytime.
However, your key
and value
are just there to append those to the dictionary. Since the dictionary is storing the keys and corresponding values, you don’t need to save the key
and value
input arguments so that you can use them somewhere else in the Class.
Hopefully, this starts to clear it up a bit.
That’s a good explanation. Thanks
1 Like