试图找到第10,001个素数。这就是我所拥有的:
def seven(count):
desired_count = count
actual_count = 6
number = 15
while desired_count > actual_count:
factors_in_number = range(int((number**.5)+1))
_factors_in_number = factors_in_number[2:]
print "prime count:"
print actual_count
print "current number:"
print number
print "factors:"
print _factors_in_number
if number % any(_factors_in_number) == 0:
number += 2
break
elif number % all(_factors_in_number) != 0:
actual_count += 1
number += 2
return number
我试图通过"任何"等因素列表来缩短搜索范围。而我正在尝试别的,但后来做了elif。 IDK。 这就是我得到的:
seven(10001)
prime count:
6
current number:
15
factors:
[2, 3]
prime count:
6
current number:
17
factors:
[2, 3, 4]
prime count:
6
current number:
19
factors:
[2, 3, 4]
prime count:
6
current number:
21
factors:
[2, 3, 4]
prime count:
6
current number:
23
factors:
[2, 3, 4]
prime count:
6
current number:
25
factors:
[2, 3, 4, 5]
prime count:
6
current number:
27
factors:
[2, 3, 4, 5]
因此,列表因素正确增加,数量增加,但素数不计,它与任何人和所有人有关。那么我如何使用任何和所有错误?
我知道肯定有更快的方法,但我试图让我的怪物离开地面。谢谢!干杯
答案 0 :(得分:4)
由于actual_count
和any
未按预期使用,因此您未获得all
。实际上,永远不会执行以下elif
块:
elif number % all(_factors_in_number) != 0:
actual_count += 1
number += 2
因为all(_factors_in_number)
在以这种方式应用时始终为True
且 any_number mod 始终为零,因为True
被强制为1.所以条件永远不会过去。只要您的容器 非空,就会传递any
块。
您可能打算将检查执行为:
elif all(number % some_integer!=0 for number in _factors_in_number):
actual_count += 1
number += 2
确保对容器的所有成员执行mod
操作,all
强制执行所有成员的条件。相同的更新应适用于any
。
答案 1 :(得分:2)
使用all(_factors_in_number)
或any(_factors_in_number)
绝对不会给出您认为的结果:
>>> any([1,2,3,4])
True
>>> 7 % any([1,2,3,4]) #True is treated like 1
0
请尽快查看help(any)
,看看它是如何运作的:
>>> help(any)
Help on built-in function any in module builtins:
any(iterable, /)
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
因此,为了正确使用函数,条件需要在调用内部循环,如下所示:
if any(number%i == 0 for i in _factors_in_num):
#and then
if all(number%i != 0 for i in _factors_in_num):