Ich habe ein kleines Problem mit zwei verschiedenen Klassen und zwei Methoden aus der gleichen Klasse. Ich habe eine Klasse B, die beide Methoden aus Klasse A verwendet, die gut zu funktionieren scheint. Das Problem ist jedoch, dass die erste Methode aus der Klasse a (insert) eine Liste ändert, die die zweite Methode (lookup) aus dieser Klasse verwenden soll. Es verwendet die globale Liste, die immer noch nur mit Nullen eingeleitet wird. Also habe ich keine Ahnung, wie ich die HashMap-Methode von der Insert-Methode aus verwenden soll:/Ich hoffe, dass jemand helfen kann, danke!Python - Zugriff auf eine Liste von einer anderen Klassenmethode
""" PUBLIC MEMBERS
Insert the given key (given as a string) with the given value (given as
an integer). If the hash table already contains an entry for the given key,
update the value of this entry with the given value.
"""
class Map:
global m
m = 10000
global HashMap
HashMap = []
for i in range(m):
HashMap.append(0)
@classmethod
def insert(self, key, value):
"""
>>> Map.insert("hi", 9)
[4,53]
"""
self.key = key
self.value = value
asci = 0
for i in key:
asci += ord(i)
hashindex = (asci%m)*2
print(hashindex)
print(HashMap[hashindex])
if HashMap[hashindex] == key:
HashMap[hashindex + 1] = value
else:
while HashMap[hashindex] != 0:
hashindex = ((asci+1)%m)*2
HashMap[hashindex] = key
HashMap[hashindex+1] = value
""" Check if there exists an entry with the given key in the hash table.
If such an entry exists, return its associated integer value.
Otherwise return -1.
"""
@classmethod
def lookup(self, key):
self.key = key
ascilookup = 0
for i in key:
ascilookup += ord(i)
indexlookup = (ascilookup%m)*2
for j in HashMap:
if HashMap[j]==key:
return HashMap[j + 1]
elif HashMap[j]==0:
return "-1"
else:
j =((j+1)%m)*2
if __name__ == "__main__":
import doctest
doctest.testmod()
Warum Sie verwenden eine Liste, um eine Hashmap zu ersetzen? Verwende ein [dictionary] (https://learnpythontehardway.org/book/ex39.html) – pointerless