简体   繁体   English

即使我返回了所有内容,我的代码的递归似乎也不起作用

[英]Recursion for my code doesn't seem to work even though I am returning everything

I am making code to check if a number is a prime or not, but I want the argument to be both list and integer.我正在编写代码来检查一个数字是否为素数,但我希望参数既是列表又是整数。 For that I'm using recursion but the recursion doesn't seem to work.为此,我正在使用递归,但递归似乎不起作用。

 def prime_checker(suspected_prime):
    if type(suspected_prime) == type(list()):
        result_list = list()
        for x in range(len(suspected_prime)):
            result_list.append(prime_checker(suspected_prime[x]))
        return(result_list)
    else:
        prime_factor, factors, suspected_prime = 2, 0, abs(suspected_prime)
        while factors < 1:
            if suspected_prime % prime_factor == 0:
                factors += 1
            if math.ceil(suspected_prime**0.5) == prime_factor:
                if factors == 0:
                    return True
                else:
                    return False
            prime_factor += 1 

I think this should work for your code:我认为这应该适用于您的代码:

def prime(suspected_prime):
if type(suspected_prime) == list:
    result_list = list()
    for x in suspected_prime:
        result_list.append(prime(x))
    return(result_list)
else:
    factors,suspected_prime = 0,abs(suspected_prime)
    root = int(suspected_prime**0.5)
    for x in range (2,(root+1)):
        if(factors == 1):
            break
        elif(suspected_prime%x == 0):
            factors = 1  
            return False

    if (factors == 0):
        return True

You can change the if-else statement according to your requirement if you want.如果需要,您可以根据需要更改 if-else 语句。

Both your list case and int case are too complicated if not broken, let's see what we can do.你的list case 和int case 都太复杂了,如果不坏的话,让我们看看我们能做些什么。 First, use isinstance to test types.首先,使用isinstance来测试类型。 Next, you don't need to loop over the indexes, you can more easily loop over the content.接下来,您不需要遍历索引,您可以更轻松地遍历内容。

As far as the int clause, you continue doing math after the answer is already known -- don't waste time this way when it comes to primes.至于int子句,您在知道答案后继续进行数学运算——当涉及到素数时,不要以这种方式浪费时间。 Also, this style of prime testing is always simpler if we treat numbers 2 and less, and evens, as special cases and focus on testing odd divisors only:此外,如果我们将数字 2 及以下以及偶数视为特殊情况,并且只专注于测试奇数除数,则这种质数测试风格总是更简单:

def prime_checker(suspected_primes):
    if isinstance(suspected_primes, list):
        return [prime_checker(entity) for entity in suspected_primes]

    suspected_prime = abs(suspected_primes)

    if suspected_prime < 2:
        return False

    if suspected_prime % 2 == 0:
        return suspected_prime == 2

    for divisor in range(3, int(suspected_prime**0.5) + 1, 2):
        if suspected_prime % divisor == 0:
            return False

    return True

print(prime_checker([1, [2, 3], 4, [5, 6, [7, 8], 9]]))
print(prime_checker(13))

OUTPUT输出

> python3 test.py
[False, [True, True], False, [True, False, [True, False], False]]
True
>

Currently you have :目前你有:

def prime-checker (input could be scalar or a list)

Strategy 1 : (Remove the looping inside prime-checker, always deal with a scalar, ie non-list).策略 1 :(删除素数检查器内部的循环,始终处理标量,即非列表)。 so you have :所以你有了 :

def prime_checker (scalar, ie. non-list input arg) :

To handle this, change your implementation to always handle a scalar.要处理此问题,请将您的实现更改为始终处理标量。 Do your looping externally, outside the prime-checker function.在素数检查器函数之外进行外部循环。 With this your prime-checker will only have the math calculation part, so it will be simpler and easier to understand.有了这个,您的素数检查器将只有数学计算部分,因此它会更简单,更容易理解。

Strategy 2: Alternately, if you insist on keeping the list looping inside prime-checker.策略 2:或者,如果您坚持在素数检查器中保持列表循环。

Case 1 : if your input is just a number , say 45. Then send the input arg as [45] So , the external invocation of prime-checker (from the external caller) would become情况 1:如果您的输入只是一个数字,例如 45。然后将输入 arg 发送为 [45] 因此,素数检查器的外部调用(来自外部调用者)将变为

results = prime_checker( [45])

Case 2: If your input is a list, say list1, then your invocation is情况 2:如果您的输入是一个列表,比如说 list1,那么您的调用是

results = prime_checker (list1).

So, now your implementation always expects and deals with a list.所以,现在你的实现总是期望并处理一个列表。

# we always get input as a list (hence I changed the arg name)
 def prime_checker(suspected_list):
    # this branch *looks* recursive, but actually only handles a list
    if (len(suspected_list) > 1) :
        result_list = []
        for prime_candidate in suspected_list:
            result_list.append(prime_checker([prime_candidate]) # recur, as a list
        return(result_list)
    else: (when suspected list has only 1 entry)
        # this branch does the actual prime calculation for a single input
        suspected_prime = suspected_list[0]
        prime_factor, factors, suspected_prime = 2, 0, abs(suspected_prime)
        while factors < 1:
            if suspected_prime % prime_factor == 0:
                factors += 1
            if math.ceil(suspected_prime**0.5) == prime_factor:
                if factors == 0:
                    return True
                else:
                    return False
            prime_factor += 1 

暂无
暂无

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

相关问题 即使我正确输入了所有内容,我也无法理解为什么我会收到元组错误 - Can't understand why I am getting tuple error even though I typed everything correctly 我必须编写线性搜索代码,但我的代码似乎无法正常工作 - I have to code a linear search but my code doesn't seem to work 即使我导入了硒,硒也不起作用 - Selenium doesn't work even though I imported it 即使一切似乎都很好,我也会得到一个定义的错误 - I am getting a defined error even though everything seems to be fine 使用tkinter,.get()方法似乎不适用于我的代码 - With tkinter, the .get() method doesn't seem to work with my code 我正在尝试制作烛台图,但即使代码似乎有效,图表也不会出现在任何地方 - I am trying to make candlestick graphs, but even though the code appears to work, the charts don’t show up anywhere 递归 - 楼梯问题 - 为什么我的代码不起作用? - Python - Recursion - Stairs Problem - Why doesn't my code work? - Python RegEX似乎不匹配,即使它应该匹配 - RegEX doesn't seem to match, even though it should 我尝试调试此代码,但似乎无法正常工作 - I have tried debugging this code but it doesn't seem to work 我想找到数字中数字的平方和,我的代码适用于正数但似乎不适用于负数 - I want to find the sum of squares of digits in a number, my code work fine for positive numbers but doesn't seem to work with negative numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM