简体   繁体   English

返回False以退出循环

[英]Returning False to Break out of a loop

I am trying to break out of this loop. 我正在尝试摆脱这种循环。 I have returned False and added a break if the character in the word is not on the hand, which is a dictionary with integer values per letter, based on Scrabble letter scores. 如果单词中的字符不在手上,我将返回False并添加一个中断,这是根据拼字字母得分对每个字母都具有整数值的字典。 This is part of a larger game but this particular function checks to see if the word I've entered is valid. 这是大型游戏的一部分,但该特定功能检查我输入的单词是否有效。

Now the issue I'm having is if the word entered is not in the word list the input is rejected and the player is asked to enter another word. 现在我遇到的问题是,如果输入的单词不在单词列表中,则输入被拒绝,并且要求播放器输入另一个单词。 HOWEVER...if I enter a single letter for instance, the hand is still updated to have that letter removed, and is therefore not available when I retype a word using all three letters. 但是...例如,如果我输入一个字母,那只手仍会更新以删除该字母,因此当我使用所有三个字母重新输入一个单词时,该手将不可用。

For example: 例如:

if my hand is rut 如果我的手发情

and I enter u, my word will be invalid, but the hand now contains only r t. 当我输入u时,我的单词将无效,但该手现在仅包含r t。 Therefore rut will no longer be available. 因此,车辙将不再可用。

I have a pretty good grasp of the loops and return statements after the last 24 hours straight of coding, except I can't figure out how to structure this loop to avoid that issue. 在最近24小时的编码之后,我对循环和return语句有了很好的了解,但我不知道如何构造该循环来避免该问题。

Here is the code: 这是代码:

def is_valid_word(word, hand, word_list):
"""
Returns True if word is in the word_list and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or word_list.

word: string
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""

    remaining = hand
    for c in word:
        if c not in remaining.keys():  """Loop 1"""
            return False
            break
        if c in remaining.keys():     """Loop 2"""
            remaining [c] -= 1
        if remaining [c] < 0:       """Loop 3"""
            return False
    if word in word_list:
        return True
    else:
        return False

However I structure the loops eventually a condition will fail. 但是,我构造了循环,最终条件将失败。 If I indent Loop 2 and 3 then they'll fail if the letter is not in the hand, and vice versa. 如果我缩进循环2和3,则如果字母不在手中,它们将失败,反之亦然。 Obviously a simple fix would be something like break(n loops) but that doesn't exist in Python. 显然,一个简单的解决方法是使用break(n loops)之类的方法,但是在Python中不存在。 Any suggestions to make this happen? 有什么建议可以做到这一点? I've been working on it a long time as I'm new to programming. 我从事编程工作已经很长时间了。

Thanks in advance! 提前致谢!

There are several problems in your code, I have refactored it to make it clearer (and fixed it, that was the point :)) 您的代码中存在几个问题,我对其进行了重构以使其更清晰(并加以修正,这才是要点:))

minor issues : 小问题

  • not optimal: first check if word is in word_list (you'd better use a set rather than a list, would be much faster), then test for available letters 并非最佳选择:首先检查word是否在word_list中(最好使用set而不是列表,这样会更快),然后测试可用字母
  • several return statements, followed by break . 几个return语句,然后是break Confusing. 令人困惑。

major issue : 主要问题

The main problem being that you affect remaining to hand and you change it, thus destroying your head each time you call the function which explains the behaviour you're experiencing. 主要问题是,影响hand remaining并对其进行更改,从而在每次调用该函数来解释您所遇到的行为时都损坏了head

You have to copy the dictionary, and it will work. 您必须复制字典,它将起作用。 Python parameters are passed by reference, so if you pass a list or a dict and you modify it within the function, then it remains modified, unless you make a copy of it. Python参数是通过引用传递的,因此,如果传递listdict并在函数中对其进行修改,则除非您对其进行复制,否则它将保持修改状态。

No real problems with the break & returns: my idea is that you think it does not work when you call your function several times in a row, when first call just destroys your input data. 中断和返回没有真正的问题:我的想法是,当您多次连续调用函数,而第一次调用只是破坏您的输入数据时,您认为它不起作用。

def is_valid_word(word, hand, word_list):
    """
    Returns True if word is in the word_list and is entirely
    composed of letters in the hand. Otherwise, returns False.
    Does not mutate hand or word_list.

    word: string
    hand: dictionary (string -> int)
    word_list: list of lowercase strings
    """
    # make a copy or hand is destroyed by your test
    remaining = hand.copy()  
    rval = False

    if word in word_list:
        rval = True
        # don't check if word is not in word_list (optim)
        for c in word:
            if c not in remaining: # no need to specify keys()
                rval = False
                break

            remaining [c] -= 1
            if remaining [c] < 0:
                rval = False
                break

    return rval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM