简体   繁体   English

使用递归确定半完美数

[英]Using recursion to determine a semiperfect number

I am in need of your help again.我再次需要你的帮助。 I'm writing a code that determines whether a number is a semiperfect number or not by returning a boolean value.我正在编写一个代码,通过返回一个布尔值来确定一个数字是否是一个半完美数字。 So first I thought I would make a list of the factors of the number excluding the number itself所以首先我想我会列出除数字本身之外的数字因素

def isSemiPerfect(n):
factor = []
for i in range(n-1, 0, -1):
    if n%i == 0:
        factor.append(i)

If I were to check for the number 12, it would return如果我要检查数字 12,它会返回

factor = [1, 2, 3, 4, 6]

Then I need to make a code to use recursion to check if you add certain numbers it would be equal to 12然后我需要编写一个代码来使用递归来检查你是否添加了某些数字它等于 12

True = 6 + 4 + 2 or 6 + 3 + 2 + 1

Can someone tell me how I can use recursion to do trial and error?有人可以告诉我如何使用递归进行反复试验吗? Like I'll always start with the biggest number and try a path with the next biggest number until I've tried all combinations.就像我总是从最大的数字开始,然后尝试使用下一个最大数字的路径,直到我尝试了所有组合。

I know there isn't a lot to go on with I just hope that you can tell me how I can use recursion effectively.我知道没有很多事情要做,我只是希望您能告诉我如何有效地使用递归。 Thank you!谢谢!

You can think about it this way.你可以这样想。

The question "Can [1,2,3,4,6] sum to 12"?问题“[1,2,3,4,6] 的总和可以为 12”吗?

Is the same as "Can [2,3,4,6] sum to 11" or "Can [2,3,4,6] sum to 12"?与“[2,3,4,6] 可以和为 11”还是“[2,3,4,6] 可以和为 12”相同吗?

One uses the first element (and has lower sum) and the other does not use the first element and has the same sum.一个使用第一个元素(并且总和较低),另一个不使用第一个元素并具有相同的总和。

so a start function would be:所以一个启动函数是:

def f(lst,sum_left):
    return f(lst[1:], sum_left-lst[0]) or f(lst[1:],sum_left)

However, this function does not know when to stop.但是,这个函数不知道什么时候停止。 So we need some base cases .所以我们需要一些基本情况

Obviously, if sum is 0, the answer is trivially yes:显然,如果 sum 为 0,那么答案是肯定的:

if sum_left == 0:
    return true

Another base case is, if the sum is < 0, we have taken a too big element and we can never recover.另一个基本情况是,如果总和 < 0,我们采用了一个太大的元素,我们永远无法恢复。

if sum_left < 0:
    return true

Also, we can risk running out of elements like [1,2] can never sum to 50, so we add a base case if there are no elements in the list:此外,我们可能会冒用完元素的风险,例如 [1,2] 永远不会总和为 50,因此如果列表中没有元素,我们会添加一个基本情况:

if not lst:
    return false

Putting it all together:把它们放在一起:

def f(lst, left):
    if left == 0:
        return True
    if left < 0:
        return False
    if not lst:
        return False
    
    return f(lst[1:],left-lst[0]) or f(lst[1:],left)

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

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