【问题标题】:How to fix recursion function [duplicate]如何修复递归函数[重复]
【发布时间】:2019-08-10 21:29:05
【问题描述】:

我正在尝试编写一个递归函数,它以整数作为参数并返回整数中总和为 10 的数字对的数量。例如,findPairs(28164730) 将返回 3,因为 2+8=10 , 6+4=10, 7+3=10。
这就是我的代码现在的样子:

def find(x):
    x = str(x)
    count = 0
    if str((10 - int(x[0]))) in x:
        count = count + 1
        x = x[1:]
        find(x)
    elif len(x) > 1:
        x = x[1:]
        find(x)
    return count

我遇到的问题是该函数将始终返回计数为 1,因为我再次调用它以进行递归,并且它将计数设置回 0,而不是每次配对时将计数加 1成立。有谁知道我该如何解决这个问题?

【问题讨论】:

  • 555 怎么样?您会将(5,5) 视为一对还是三个不同的对?

标签: python recursion


【解决方案1】:

现在,您的代码没有使用递归 find 调用的返回值;它只是打电话给find(x)。这将解决您的问题:

def find(x):
    x = str(x)
    count = 0
    if str((10 - int(x[0]))) in x:
        # count = count + 1
        x = x[1:]
        count = 1 + find(x)
    elif len(x) > 1:
        x = x[1:]
        count = find(x)
    return count

【讨论】:

  • 完美,非常感谢!
【解决方案2】:

一种可能的解决方案是通过例如简化根本不使用递归。参见例如以下尝试:

def find(x):
    x = str(x)
    count = 0
    for i in range(len(x)-1):

        if str((10-int(x[i]))) in x[i+1:]:
            count += 1

    return count

【讨论】:

  • 也许ctr = {int(d): c for d, c in Counter(x).items()}return sum(ctr[i] * ctr.get(k-i,0) for i in ctr) // 2O(N)
  • 感谢您,但我正在尝试通过解决其中一些练习问题来练习递归,感谢您的帮助!
【解决方案3】:

要么有一个单独的函数声明count 然后调用find(),要么将count 设置为全局变量。我认为第一种方法更可取。

def get_count(x):
  count = 0
  find(str(x))
  return count

或者类似的东西。此外,如果您使用该方法,请确保从原始 find 函数中删除 count = 0

【讨论】:

  • 全局变量通常是a bad idea
  • 是的,这就是为什么我说第一种方法更可取。
猜你喜欢
  • 2022-01-03
  • 2013-10-31
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
  • 2015-03-04
  • 2016-05-06
  • 2016-02-01
相关资源
最近更新 更多