我觉得这个问题需要某种递归。这是一个数据结构类,教我们如何处理哈希表中的冲突。我们被要求:
如果你没有成功地放置一个单词,保持你所达到的g值。
当您不成功地放置一个单词并需要回溯时:首先-从散列表中的当前位置移除该单词,然后将第一个字母的g值递增1,这样当您尝试放置它时,它不会回到相同的位置。
我的解决方案是使用两个while循环,一个控制我们使用的单词,另一个循环来计数尝试。它可在以下方面找到:
#Placing in hash table
hashTable = [None] * len(keyWords)
attempt = 0
i = 0
while(i <= len(keyWordsList) - 1 | i>= 0) :
word = keyWordsList[i] #cycling thru list of lists picking first element which is a word
colCount = 0
# print("\nattempting to hash:", word[0])
if hashTable[hash(word[0], 0)] != None: #uses hash function checked working as expected returns index
while(colCount <= maxGVal) : #to ensure the spot is free in the table
#print("\n collision occurred on word: ", word[0], "Slot: ", word.index(word[0]))
if hashTable[hash(word[0], colCount)] == None:
hashTable[hash(word[0], colCount)] = word[0]
#print("successfully hashed: ", word[0], "at slot:", hash(word[0], colCount))
elif colCount == maxGVal:
#print("resetting gvals:")
#for sublist in gVals:
# sublist[1] = 0
print("going back to previous word:")
colCount = 0
i -= 1
break
colCount += 1
elif hashTable[hash(word[0], 0)] == None:
hashTable[hash(word[0], 0)] = word[0]
#print("Successfully hashed: ", word[0], "at slot:", hash(word[0], 0))
i += 1 发布于 2020-07-07 23:38:15
我的散列函数出现了错误,并对while循环进行了过度考虑。最大的错误是访问列表时错误地注意到了新代码中的两个括号。对于任何对未来感兴趣的人,我有下面使用的循环。这个项目在大学里到处传阅,给你带来了好运。无论何时我都可以在这里发表更多的代码。
while(j <= len(keyWords)-1):
aWord = keyWordsList[j][0]
if hashTable[hash(aWord, colCount)] == None:
hashTable[hash(aWord, colCount)] = aWord
if colCount > 0: colCount = 0
j += 1
continue
elif hashTable[hash(aWord, colCount)] != None:
colCount += 1
elif colCount == maxGVal:
for sublist in gVals:
sublist[1] = 0
j -= 1
colCount = 0https://stackoverflow.com/questions/62526294
复制相似问题