2017-06-26 30 views
1

我的哈希码仅返回单词的整个标题。 我想使它显示的结果只使用关键字 至少2个单词(向前),然后显示结果(获取函数)。搜索关键字而不是整个单词 - py

我的哈希码

class hashin: 
def __init__(self): 
    self.size = 217 # size of hash table 
    self.map = [None] * self.size 

def _get_hash(self, key): 
    hash = 0 
    for char in str(key): 
     hash += ord(char) 
    return hash % self.size 
#returns the ASCII value of char in str(key) 

def add(self, key, value): # add item to list 
    key_hash = self._get_hash(key) 
    key_value = [key, value] 
    if self.map[key_hash] is None: 
     self.map[key_hash] = list([key_value]) 
     return True 
    else: 
     for pair in self.map[key_hash]: 
      if pair[0] == key: 
       pair[1] = value 
       return True 
     self.map[key_hash].append(key_value) 
     return True 

def get(self, key): # search for item 
    key_hash = self._get_hash(key) 
    if self.map[key_hash] is not None: 
     for pair in self.map[key_hash]: # find pair of words 
      if pair[0] == key: # if pair is equals to the whole title of the word 
       return pair[0] + " - " + pair[1] 
    return "Error no results for %s \nEnter the correct word." % (key) 

样本输出:

当整个标题被输入

Sample Output search (needs to have the whole word in order to show)

当关键词被输入(我需要即使对显示结果关键字被打字)

no results when keyword is typed

我需要的是: 输出: 骗子 - Kygos ,其余的单词与谢在他们的名字

+0

你可以更好地解释,你可以显示输入和输出的例子来更好地了解您。 – eyllanesc

+0

除此之外,与pyqt有关系,因为示例不需要pyqt的功能,因为它显示您的代码。 – eyllanesc

+0

对不起,我会尝试再次重新显示我的问题,然后发布关于它的图片 –

回答

1

哈希表是不是该任务的正确的数据结构。散列值的目的是将搜索范围缩小到可能性的一小部分。由于散列值依赖于整个字符串,因此仅使用字符串的一部分会给出错误的子集。

此任务的更好数据结构是trie(有时称为“前缀树”)。虽然自己编写这个数据结构并不难,但PyPI上已经有很多经过测试的,现成可用的模块。

参见: https://pypi.python.org/pypi?%3Aaction=search&term=trie&submit=search