首页 > 解决方案 > Python 我明确返回 None 但什么也没得到

问题描述

我在基本情况下明确返回None,但 doctest 告诉它什么都没有

这是我的代码:

def find_triple(ilist):
    """ Find a triple of integers x, y, z in the list ilist such that x + y = z.
    Return the tuple (x, y). If the triple does not exist, return None.

    >>> find_triple([4,5,9]) in [(4,5), (5,4)]
    True
    >>> li = [(30,70), (70,30), (20,50), (50,20), (20,30), (30,20)]
    >>> find_triple([20,40,100,50,30,70]) in li
    True
    >>> find_triple([6,11,7,2,3])
    None
    >>> find_triple([1, 1, 3])
    None
    """
    # define a yield function to reduce the cost of time and space
    def yield_pair(ilist):
        """ enumerate all the two pairs in the list.

        >>> g = yield_pair([4,5,9])
        >>> next(g)
        (4, 5)
        >>> next(g)
        (4, 9)
        >>> next(g)
        (5, 9)
        >>> next(g)
        Traceback (most recent call last):
        ...
        StopIteration
        """
        for i in range(len(ilist) - 1):
            for j in range(i, len(ilist) - 1):
                yield (ilist[i], ilist[j + 1])

    # first turn the ilist into a set, so the `in` operation is much more efficient
    iset = set(ilist)
    g = yield_pair(ilist)
    while True:
        try:
            pair = next(g)
            if sum(pair) in iset:
                return pair
        except StopIteration:
            return None  # ********  problems here ****************
        except:
            return None  # ******** verbose I just try to show that it does not return None *******

这是我的错误信息:

Failed example:
    find_triple([6,11,7,2,3])
Expected:
    None
Got nothing

标签: pythonpython-3.x

解决方案


REPL 总是忽略None作为返回值,不打印任何内容。跳过该行的输出或显式打印返回值。


推荐阅读