【发布时间】:2014-09-28 12:43:46
【问题描述】:
我目前正在完成我的计算机科学作业,但在最后一点上遇到了问题,我正在寻求一些建议。
使用以下类:
class CounterLinkedList:
__n_comparisons__ = 0
def __init__(self, head=None):
self.head = head
self.__n_accesses__ = 0
def __repr__(self):
node = self.head
string = str(node)
while node.next_node:
string += " -> " + str(node.next_node)
node = node.next_node
string = "[" + string + "]"
return string
class MyString:
'''A wrapped string that counts comparisons of itself
against strings and delegates all other operations to the
string itself.'''
def __init__(self, i):
self.i = i
def __repr__(self):
return repr(self.i)
def __getattr__(self, attr):
'''All other behaviours use self.i'''
return self.i.__getattr__(attr)
class CounterNode:
def __init__(self, word, count=1):
self.word = MyString(word)
self.count = count
self.next_node = None
def __repr__(self):
return str(self.word) + ": " + str(self.count)
def _c_mul(a, b):
"""Substitute for c multiply function"""
return ((int(a) * int(b)) & 0xFFFFFFFF)
def nice_hash(input_string):
"""Takes a string name and returns a hash for the string. This hash value
will be os independent, unlike the default Python hash function."""
if input_string is None:
return 0 # empty
value = ord(input_string[0]) << 7
for char in input_string:
value = _c_mul(1000003, value) ^ ord(char)
value = value ^ len(input_string)
if value == -1:
value = -2
return value
def hash_word(item, slots):
return nice_hash(item) % slots
我需要在不使用字典的情况下实现一个哈希表,每次你从单词列表中取出一个单词时,你都会检查它是否在哈希表中,如果是则增加它的计数。如果不是,则将其计数插入表中,如果哈希表槽中已经存在对象,则使用链接。链接是通过链表完成的。
如果我使用输入,代码的输出:
slots = 3
counts, comparisons = word_counter_hash(['list', 'with', 'no', 'repeat', 'words'], slots)
for i in range(slots):
print(str(i) + ": " + str(counts[i]))
print(comparisons)
应该输出:
0: ['words': 1 -> 'no': 1 -> 'list': 1]
1: ['repeat': 1]
2: ['with': 1]
3
到目前为止我的代码是:
'''test'''
from classes_2 import CounterNode, CounterLinkedList, hash_word
def word_counter_hash(words_list, slots):
"""test"""
hash_list = [None]*slots
num_comparisons = 0
for new_word in words_list:
if len(words_list) >= 0:
n = CounterNode(new_word, 1)
new_list = CounterLinkedList(n)
hash_value = hash_word(new_word, slots)
if hash_list[hash_value] == None:
del hash_list[hash_value]
hash_list.insert(hash_value, new_list)
else:
first_node = new_list.head
first_node.next_node = CounterNode(words_list[hash_value], 1)
first_node = (new_list)
del hash_list[hash_value]
hash_list.insert(hash_value, new_list)
return hash_list, num_comparisons
但是我的输出和上面的不一样:
0: ['words': 1 -> 'list': 1]
1: ['repeat': 1]
2: ['with': 1]
0
我正在寻求任何关于我可以做些什么来走上正轨的建议,我们将不胜感激。
【问题讨论】:
-
这段代码有点长。是否有可能削减一点,还是全部都需要?
-
@Veedrac,不幸的是需要巨大的类代码,因为它限制了分配,以及我们制定答案的基础
-
assignment 可能需要它,但现在我们只需要重现该错误。删除与此无关的内容会有所帮助。
-
@Veedrac 对此感到抱歉,我已尽量减少它
标签: python hash linked-list nodes