2017-05-20 5 views
1

私は同じクラスから2つの異なるクラスと2つのメソッドに少し問題があります。クラスAの両方のメソッドを使用しているクラスBがあります。これはうまく動作するようです。 ただし、クラスa(挿入)の最初のメソッドは、このクラスの2番目のメソッド(ルックアップ)が使用するリストを変更します。まだゼロだけで開始されているグローバルリストを使用しています。だから私はどのようにメソッドを挿入メソッドからHashMapを使用するように指示するか分からない:/私は誰かが助けてくれることを願っています、ありがとう!Python - 別のクラスメソッドからのリストへのアクセス

""" 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() 
+0

なぜあなたが使用していますハッシュマップを置き換えるリスト? [dictionary](https://learnpythonthehardway.org/book/ex39.html) – pointerless

答えて

0

これは、Pythonでのマップのはるかに簡単な実装です:

class Map: 
    HashMap = {} 

    def __init__(self,leng): 
     for i in range(leng): 
      self.HashMap[str(i)]=0 

    def insert(self, key, value): 
     self.HashMap[key]=value 


    def lookup(self, key): 
     for each in self.HashMap.iterkeys(): 
      if each == key: 
       return self.HashMap[each] 
     return None 

EDIT辞書を使用せずに、二つのリストを使用して簡単です:

class Map: 
    keys = [] 
    values = [] 

    def __init__(self,leng): 
     for i in range(leng): 
      self.keys.append(str(i)) 
      self.values.append(0) 

    @classmethod 
    def insert(self, key, value): 
     self.keys.append(key) 
     self.values.append(value) 

    @classmethod 
    def lookup(self, key): 
     for x in range(0, len(self.keys)): 
      if self.keys[x] == key: 
       return self.values[x] 
     return None 
+0

ありがとう、問題は、私は内部の辞書を使用することができません:/ – Kuroskai

+0

ああ、それはそれを説明します。おそらく2つのリストを使用するでしょうか? – pointerless

+0

辞書を使用せずに2番目のソリューションを追加しました – pointerless

関連する問題