python-3.x - 如何在“列表”中打印素数
问题描述
我已经从用户那里获得了输入并将其因素放入一个新列表中。我如何检查列表中的素数。
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
print(b)
解决方案
在这里,您可以打印因子列表,然后遍历因子列表,该程序将打印出素数。print(n)
除了打印它,您还可以通过用其他东西替换它来将它附加到另一个列表中。
import math
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
print(b)
def is_prime(n): #calling a function
if n == 2:
print(n) #if one of the factors is 2 it prints it because it is a prime number
if n % 2 == 0 or n <= 1: # if it is less than one or is a factor of 2 it returns false and does nothing
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2): #checks for other divisors
if n % divisor == 0:
return False
print(n) #otherwise it prints out the number since it is a prime number
for n in b: #iterates through the list of factors and checks if they are prime
is_prime(n)
如果我们运行这个并且我输入 10 它会返回这个:
[2, 5]
2
5
编辑:当您输入一个素数时,它会返回一个空白数组。所以我将代码编辑为:
import math
values = []
def is_prime(n): #calling a function
if n == 2:
values.append(n)
#print(n) #if one of the factors is 2 it prints it because it is a prime number
return True
if n % 2 == 0 or n <= 1: # if it is less than one or is a factor of 2 it returns false and does nothing
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2): #checks for other divisors
if n % divisor == 0:
return False
#print(n) #otherwise it prints out the number since it is a prime number
values.append(n)
return True
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
if is_prime(a)==True: #if the inputted number is prime it automatically appends that number to the list and breaks since prime numbers don't have any other factors
b.append(a)
break;
print(b)
for n in b: #iterates through the list of factors and checks if they are prime
is_prime(n)
def remove_duplicates(values): #here it checks for duplicates
output = []
seen = set()
for value in values:
# If value has not been encountered yet,
# ... add it to both list and set.
if value not in seen:
output.append(value)
seen.add(value)
return output
# Remove duplicates from this list.
values = remove_duplicates(values)
print("Here are the prime factors :")
print(values) #prints out the values
现在,如果您输入一个素数,它会返回:
[7]
Here are the prime factors :
[7]
以及任何其他数字,例如 20 :
[2, 4, 5, 10]
Here are the prime factors :
[2, 5]
仍会运行。注意:我将其从仅打印数字更改为将数字附加到数组然后打印出数组。
推荐阅读
- python - 使用python计算肽单同位素
- c# - 尝试不每秒创建新文件,但如果文件限制超过则使用 log4net 创建新文件
- windows - 使用不带方括号的 dir /D 命令作为输出
- haskell - Haskell 中使用 List Monad 的下推自动机
- java - 如何分配多维输出缓冲区来提供 Android Tflite 的interpreter.run()?
- django - 忽略 Django 中的可疑文件操作
- c# - 应用程序在后台时如何正确通知当前视图模型有关推送通知
- vba - SSRS - 如何使用 3 个 if 语句,其中一个是空值
- sql-server - 通过从表格中的单元格运行脚本来分配变量
- c# - MSTest ThrowsException 与异常对象的条件?