如何在while循环中进行“回溯”?

2024-09-29 00:06:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我觉得这个问题需要某种递归。这是一个数据结构课程,教我们如何处理哈希表中的冲突。我们被要求:

  • 最大尝试次数为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        

Tags: toinnonelenistablehash单词
1条回答
网友
1楼 · 发布于 2024-09-29 00:06:04

我的散列函数出错,同时过度思考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

相关问题 更多 >