【问题标题】:How can I tell what value my function is returning in Python?如何判断我的函数在 Python 中返回的值是什么?
【发布时间】:2016-10-28 10:53:11
【问题描述】:

我正在尝试调试我编写的这个程序。我如何判断给定的 wordhandword_list 是返回 True 还是 False?我尝试初始化一个变量 failure 然后修改它并打印它的值。它没有打印,所以我不知道它是否表现得像它应该的那样。任何帮助表示赞赏。

我有一个返回单词列表的函数load_words()。我知道 wordword_list 中(我检查过),所以只是想看看 word 是否完全由字典中的键中的字母组成hand,在这种情况下它不是,所以它应该返回 False。

另外,.keys() 和 .itrrkeys() 有什么区别,有没有更好的方法来循环 hand,也许用 letter, value in hand.iteritems ()?

word = 'axel'

hand2 = {'b':1, 'x':2, 'l':3, 'e':1}

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
    """
    failure = False
    if word in word_list:
        print hand
        print [list(i) for i in word.split('\n')][0]
        for letter in [list(i) for i in word.split('\n')][0]:
            print letter
            if letter in hand.keys():
                print letter
                return True
                failure = True
                print failure
            else:
                return False
                failure = False
                print failure
    else:
        return False
        failure = False
    print failure

is_valid_word(word,hand2,load_words())

更新我希望在我的函数中使用这个函数,但它给出了一个关键错误,即使它本身可以正常工作。

def update_hand(hand, word):
    """
    Assumes that 'hand' has all the letters in word.
    In other words, this assumes that however many times
    a letter appears in 'word', 'hand' has at least as
    many of that letter in it. 

    Updates the hand: uses up the letters in the given word
    and returns the new hand, without those letters in it.

    Has no side effects: does not modify hand.

    word: string
    hand: dictionary (string -> int)    
    returns: dictionary (string -> int)
    """
    for letter in [list(i) for i in word.split('\n')][0]:
        if letter in hand.keys():
            hand[letter] = hand[letter]-1
        if hand[letter] <= 0:
            del hand[letter]
    display_hand(hand)
    return hand

【问题讨论】:

    标签: python dictionary boolean


    【解决方案1】:

    它没有打印出来的原因是因为你正在返回它之前的函数prints。这意味着程序在到达print 语句之前停止。例如:

    def foo(x):
        return x
        print x
    
    foo("asdf")
    

    在以下情况下不会返回任何内容:

    def foo(x):
        print x
        return x
    
    foo("asdf")
    

    print:

    asdf
    

    所以,return 之前的所有声明。如果没有,则不会执行。

    为了您的第二次澄清,这篇文章已经有您的答案https://stackoverflow.com/a/3617008

    在 Python 2 中,iter(d.keys())d.iterkeys() 并不完全等效,尽管它们的行为相同。第一个,keys() 将返回字典的键列表的副本,iter 将在此列表上返回一个迭代器对象,第二个完整的键列表的副本永远不会构建。

    请注意,Python 3 也没有 .iterkeys()。 Python 3 使用以前的.iterkeys() 作为新的.keys()

    最后,我将按严重程度的降序查看您的代码通常存在哪些问题以及您希望实现的目标。

    1. 您的代码只检查一个字母
    2. [list(i) for i in word.split('\n')][0] 不是从一个单词中获取所有字母的方式。
    3. 您应该先返回短代码,这样您就不会出现大的缩进块。

    您的代码只检查一个字母

    在你的 for 循环中,你 return True 在检查第一个单词后立即。你应该在循环完成后return True

    for letter in word:
        if letter not in hand.keys():
            return False
    return True
    

    列表理解

    不需要你的列表理解(我稍后会告诉你为什么),也不需要那么复杂,只是为了从一个单词中获取字母。例如

    [list(i) for i in word.split('\n')][0]
    

    其实只这样做了:

    list(word)
    

    事实上,你应该直接遍历单词(就像我上面做的那样),它会一个一个地返回字母:

    for letter in word:
        # code...
    

    短代码先返回

    通常我不喜欢大块高度缩进的代码。您可以做的是首先返回短代码。例如:

    if word in word_list:
        for letter in word:
            if letter in hand.keys():
                return True
            else:
                return False
    else:
        return False
    

    可以简单写成:

    if word not in word_list:
        return False
    
    for letter in word:
        if letter in hand.keys():
            return True
        else:
            return False
    

    不过,这只是我的看法。其他一些人可能更喜欢else 语句,以便他们知道代码何时执行。

    您的最终代码如下所示:

    def is_valid_word(word, hand, word_list):
        if word not in word_list:
            return False
    
        for letter in word:
            if letter not in hand.keys():
                return False
        return True
    

    清洁对吗?但是,我假设您正在制作类似拼字游戏的游戏,因此您会计算hand 中的单词是否可以用于您选择的单词。如果单词中的字母数小于或等于您手中的字母数,您可以添加一些内容:

    def is_valid_word(word, hand, word_list):
        if word not in word_list:
            return False
        # This makes the word into a "unique list"
        letters = set(word)
        for letter in letters:
            if hand[letter] < word.count(letter):
                return False
    
        return True
    

    编辑 代码有问题。它不检查 letter 是否在 if 语句中的 hand 中:if hand[letter] &lt; word.count(letter):

    def is_valid_word(word, hand, word_list):
        if word not in word_list and word not in hand.keys():
            return False
        letters = set(word)
        for letter in letters:
            # Add this extra clause
            if letter in hand.keys() or hand[letter] < word.count(letter):
                return False
    
        return True
    

    【讨论】:

    • @sampy 查看我最近的编辑,因为我回答了您的所有问题。如果是这样,你可以接受我的回答。谢谢!
    • 这太棒了。我想知道为什么我只打印一封信,现在很清楚了。是的,我正在制作一个拼字游戏,当然,这个功能是为了确保单词是有效的。我尝试添加一个我已经创建的名为 update_hand 的函数,该函数从手上删除单词中每个出现的字母。但是,当我尝试在我的函数中使用它时,我遇到了一个关键错误,尽管它本身可以正常工作。您的函数也会引发一个关键错误,尽管只有当我在其上运行测试程序时。我将编辑我的问题以包含它,也许您可​​以提供一些见解。
    • @sampy 是的,刚刚发现问题。查看我最近的编辑。
    • 我用 hand.get(letter,None) 替换了 hand[letter],效果很好。我修改了自己的函数(用你的建议替换了干净列表理解),它似乎工作正常,除了我拥有的单元测试函数。没什么大不了的,在这种情况下,我不断地提出同样的关键错误。你的效果很好,我只是想尽我所能理解这一点。感谢您的帮助!!!
    【解决方案2】:

    您可以直接打印结果print is_valid_word(word,hand2,load_words())

    【讨论】:

      【解决方案3】:

      你有一些缩进问题,返回语句之后做一些事情是徒劳的。

      您不需要使用keysiterkeysin 运算符会为您检查,并且可以使用列表、集合、dicts(键)、元组、字符串......

      in 运算符调用大多数 python 集合支持的__contains__

      也可以看看https://docs.python.org/2/reference/expressions.html#membership-test-details

      他是你想用 3 次测试做的一个最小化的例子。

      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
      
          """
      
          if word not in word_list:
              return False
      
          for letter in word:
              if letter not in hand:
                  return False
      
          return True
      
      print(is_valid_word('bxel',
                          {'b': 1, 'x': 2, 'l': 3, 'e': 1},
                          ['foo', 'bar', 'bxel']))
      print(is_valid_word('axel',
                          {'b': 1, 'x': 2, 'l': 3, 'e': 1},
                          ['foo', 'bar', 'axel']))
      print(is_valid_word('axel',
                          {'a': 1, 'x': 2, 'l': 3, 'e': 1},
                          ['foo', 'bar', 'axel']))
      

      【讨论】:

        猜你喜欢
        • 2010-10-06
        • 1970-01-01
        • 1970-01-01
        • 2012-01-26
        • 2010-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-06
        相关资源
        最近更新 更多