首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >您如何在while循环中进行“回溯”?

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

Stack Overflow用户
提问于 2020-06-23 02:19:48
回答 1查看 420关注 0票数 1

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

  • 最大尝试次数为11次。这并不意味着g值不能超过11次。这意味着每次尝试放置单词时,都有11次尝试放置单词。

如果你没有成功地放置一个单词,保持你所达到的g值。

当您不成功地放置一个单词并需要回溯时:首先-从散列表中的当前位置移除该单词,然后将第一个字母的g值递增1,这样当您尝试放置它时,它不会回到相同的位置。

我的解决方案是使用两个while循环,一个控制我们使用的单词,另一个循环来计数尝试。它可在以下方面找到:

代码语言:javascript
复制
#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        
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-07 23:38:15

我的散列函数出现了错误,并对while循环进行了过度考虑。最大的错误是访问列表时错误地注意到了新代码中的两个括号。对于任何对未来感兴趣的人,我有下面使用的循环。这个项目在大学里到处传阅,给你带来了好运。无论何时我都可以在这里发表更多的代码。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62526294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档