[英]Find the prime and non prime numbers: Python
I am trying to modify my program to create two empty lists: prime and non_prime. 我试图修改程序以创建两个空列表:prime和non_prime。 and test if the random number in the list is a prime number or not a prime number.
并测试列表中的随机数是否是质数。 If the number is prime, I want to append it to prime number list.
如果数字是素数,我想将其附加到素数列表中。 If not, I want to be able to add it to non_prime list.
如果没有,我希望能够将其添加到non_prime列表中。 I tried to find the prime and non prime number from the random number list but I get the same output for prime and non prime number.
我试图从随机数列表中找到素数和非素数,但是素数和非素数的输出相同。 Can anyone help me?
谁能帮我?
import random
def main():
num = [random.randint(1,100) for _ in range (20)]
print(num)
lowest = min(num)
print("The lowest number is: ", lowest)
highest = max(num)
print("The highest number is: ", highest)
total = 0.0
for value in num:
total += value
average = total / len(num)
print("The average is: " , average)
prime = [num]
for a in range (1, 101):
for b in range(2, a):
if a % b == 0:
break
else:
prime.append(a)
print("The prime numbers are: " , prime)
nonprime = [num]
for x in range (1, 101):
for y in range(2, x):
if x % y == 0:
break
else:
nonprime.append(x)
print("The non prime numbers are: " , nonprime)
You could use my handy-dandy one-liner prime-checker! 您可以使用我方便的单线首选检查器!
def is_prime (x): return True if x in [2,3] else not any (x % n == 0 for n in range (2, int (x ** 0.5) + 1))
Now, you use this function in your for loop: 现在,您可以在for循环中使用此函数:
for num in range (1, 101):
if is_prime (num): prime.append (x)
else: nonprime.append (x)
BTW, if anyone wants to help me improve that function (or just wants to understand it), just comment below! 顺便说一句,如果有人想帮助我改进该功能(或者只是想了解它),请在下面评论! It pretty much makes a list of all the factors then returns true or false based on the length of that list (or True if the num is 2 or 3)
它几乎构成了所有因素的列表,然后根据该列表的长度返回true或false(如果num是2或3,则返回True)。
Just an optimization tip. 只是一个优化技巧。 In the first loop you could calculate non prime and prime both.
在第一个循环中,您可以计算非素数和素数。
def isPrime(x):
for i in range (sqrt (x)): # from i=2 till sqrt(x)
if x % i == 0: return False
return True
if isPrime (x): prime.append (x)
else: non_prime.append (x)
The above is sieve algorithm 上面是筛算法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.