简体   繁体   English

使用递归返回列表中不包括 K 和以下数字的总和

[英]Return Sum excluding K and following number in list using Recursion

My code is supposed to receive an integer and a list of integers.我的代码应该收到一个 integer 和一个整数列表。 It returns the sum of the integers in the list EXCEPT, it ignores the unlucky number and the number immediately following the unlucky number.它返回列表中整数的总和,除了,它忽略倒霉数字和紧跟在倒霉数字后面的数字。 Im only trying to use recursion (NO ITERATION).我只是尝试使用递归(无迭代)。 So far my code works for the first 5 cases but has issues with the last 2 because they have unlucky numbers at the end.到目前为止,我的代码适用于前 5 个案例,但后 2 个案例存在问题,因为它们最后有不吉利的数字。 I ma not trying to completely rewrite my function only find the error in what i currently have.我不会试图完全重写我的 function 只是在我目前拥有的内容中找到错误。

def unlucky(unlucky_num, a_list):
    """
    >>> unlucky(13,[1])
    1
    >>> unlucky(13,[1,2,3,4,5,6])
    21
    >>> unlucky(13,[13,1,2,3])
    5
    >>> unlucky(13,[1,13,2,3])
    4
    >>> unlucky(13,[13, 0])
    0
    >>> unlucky(13,[13,1,2,13,2,1,13]) #13,1,13,2,13 ignored
    3
    >>> unlucky(7,[7,4,5,7,5,4,7]) #7,4,7,5,7 ignored (7 is unlucky)
    9
    """

    if a_list == []:
        return 0
    if a_list[0] == unlucky_num:
        if len(a_list) > 1:
            return unlucky(unlucky_num, a_list[2:])
        return unlucky(unlucky_num, a_list)
    return a_list[0] + unlucky(unlucky_num, a_list[1:]) 

for the last two cases I am getting the following errors (filename redacted):对于最后两种情况,我收到以下错误(文件名已编辑):

Error
**********************************************************************
File "------", line 39, in sum_unlucky
Failed example:
    sum_unlucky(13,[13,1,2,13,2,1,13]) #13,1,13,2,13 ignored
Exception raised:
    Traceback (most recent call last):
      File "-------", line 138, in __run
        exec(compile(example.source, filename, "single",
      File "<doctest sum_unlucky[5]>", line 1, in <module>
        sum_unlucky(13,[13,1,2,13,2,1,13]) #13,1,13,2,13 ignored
      File "-------", line 50, in sum_unlucky
        return sum_unlucky(unlucky_num, a_list[2:])
      File "---------", line 52, in sum_unlucky
        return a_list[0] + sum_unlucky(unlucky_num, a_list[1:])
      File "--------", line 50, in sum_unlucky
        return sum_unlucky(unlucky_num, a_list[2:])
      File "--------", line 52, in sum_unlucky
        return a_list[0] + sum_unlucky(unlucky_num, a_list[1:])
      File "-------", line 51, in sum_unlucky
        return sum_unlucky(unlucky_num, a_list)
      File "------", line 51, in sum_unlucky
        return sum_unlucky(unlucky_num, a_list)
      File "------", line 51, in sum_unlucky
        return sum_unlucky(unlucky_num, a_list)
      [Previous line repeated 986 more times]
      File "----", line 45, in sum_unlucky
        if a_list == []: 
    RecursionError: maximum recursion depth exceeded in comparison

You really only need two tests, which will make it easier to avoid bugs.你真的只需要两个测试,这将更容易避免错误。 A test for the base case, which is an empty array and a test for the unlucky number.对基本情况的测试,它是一个空数组和对倒霉数的测试。 You don't need to test for the length after the base case because you can pass an empty array back.您不需要在基本情况之后测试长度,因为您可以传回一个空数组。 With that the function can be written in a way that it mirrors the requirements in very readable way:这样,function 可以以一种非常易读的方式反映需求的方式编写:

def unlucky(unlucky_num, a_list):
    if not a_list:                             # base case
        return 0 

    head, *rest = a_list                       # rest will be [] when len(a_list) == 1

    if head == unlucky_num:
        return unlucky(unlucky_num, rest[1:])
    return head + unlucky(unlucky_num,rest)

unlucky(7,[7,4,5,7,5,4,7])
# 9

As Mark Meyer said, it never reaches a_list == [] .正如 Mark Meyer 所说,它永远不会到达a_list == [] Try:尝试:

def unlucky(unlucky_num, a_list):
    if len(a_list) == 1:
        if a_list[0] == unlucky_num:
            return 0
        else:
            return a_list[0]
    if a_list[0] == unlucky_num:
        if len(a_list) > 1:
            return unlucky(unlucky_num, a_list[2:])
        return unlucky(unlucky_num, a_list)
    return a_list[0] + unlucky(unlucky_num, a_list[1:]) 

You forgot to exclude the unlucky number if len(a_list) == 1 .如果len(a_list) == 1 ,您忘记排除不幸的数字。 Use a_list[1:] .使用a_list[1:]

def unlucky(unlucky_num, a_list):
    if a_list == []:
        return 0

    if a_list[0] == unlucky_num:
        if len(a_list) > 1:
            return unlucky(unlucky_num, a_list[2:])
        return unlucky(unlucky_num, a_list[1:])  # <- Here
    return a_list[0] + unlucky(unlucky_num, a_list[1:])

But in that case since a_list[1:] == [] , you can skip the recursive call and just return 0 .但在这种情况下,由于a_list[1:] == [] ,您可以跳过递归调用并return 0 You could simplify that too:你也可以简化它:

def unlucky(unlucky_num, a_list):
    if a_list in ([], [unlucky_num]):
        return 0
    elif a_list[0] == unlucky_num:
        return unlucky(unlucky_num, a_list[2:])
    return a_list[0] + unlucky(unlucky_num, a_list[1:])

暂无
暂无

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

相关问题 如何通过递归获得数字列表的总和,不包括可被 3 和 7 整除的整数? - How to get the sum of a list of numbers excluding integers that are divisible by 3 and 7 with recursion? 如何修复我的代码? 使用递归,返回一个包含所有 k 的列表,使得 3 ≤ k ≤ n 并且 k 可以被 3 或 5 整除,但不能同时被 5 整除? - How can I fix my code? Using recursion, return a list containing all k such that 3 ≤ k ≤ n and k is divisible by 3 or 5 but not both? 使用递归进行 K 次交换后的最大数量 - Maximum number after K swaps using recursion 使用递归返回嵌套列表中的第二个最小数字 - Return second smallest number in a nested list using recursion 使用递归检查列表中元组的总和 - Using Recursion to check for sum of tuples in a list 使用递归查找嵌套列表的总和 - Find sum of nested list using recursion 无法在Python中使用递归调试列表总和 - Unable to debug sum of a list using recursion in Python 使用递归进行 K 次交换后返回最大值 - Return maximum value after K swaps using recursion Python 列表想要列表的总和,不包括从列表中的数字到另一个数字的值范围,在本例中为 6 到 9 - Python list that want the sum of list excluding a value range from number in the list to another number, in this case 6 to 9 使用递归从python中的单体列表生成k-mers - Generating k-mers from a list of monomers in python using recursion
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM