python - 您如何在 while 循环中进行“回溯”?
问题描述
我觉得好像这个问题需要某种递归。这是一个数据结构课程,教我们如何处理哈希表中的冲突。我们被要求:
最大尝试次数为 11。这并不意味着您的 g 值不能超过 11。这意味着您每次尝试放置单词时有 11 次尝试放置单词。
如果您放置一个单词不成功,请保留您达到的 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
解决方案
我的哈希函数有错误,同时考虑了 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 = 0
推荐阅读
- java - 如果条件不适用于 table.getValueAt JAVA swing
- facebook - FB 阻止链接到 Facebook 身份验证
- ios - 快速刷新时,错误的 UICollectionView 被加载到 Venue UITableviewCell 中
- python - If Else 在一行上得到条件表达式错误
- python - 重启后的 Django docker-compose 需要再次迁移
- vuejs2 - Vee-Validate 具有范围的自定义错误组件
- javascript - 如何禁用调整弹出窗口的大小?
- laravel - 如何与 EloquentFilter 一起执行 laravel WHERE
- android - RxJava2 Letting network call complete if fragment/activity changes
- reactjs - what is the best way to deploy react app in lan only