首页 > 解决方案 > 您如何在 while 循环中进行“回溯”?

问题描述

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

我的解决方案是使用两个 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        

标签: pythonloopsdata-structures

解决方案


我的哈希函数有错误,同时考虑了 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

推荐阅读