[英]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.