[英]prime number function python from list
Below is my code to make a prime number list from Fibonacci list, but the prime list is not working.下面是我的代码,用于从 Fibonacci 列表中创建素数列表,但素数列表不起作用。
what am I missing?我错过了什么? I need to make a prime number list from Fibonacci list.
我需要从斐波那契列表中创建一个素数列表。
a1 = []
a2 = []
count = 0
n = int(input())
def fib(n):
a = 1
b = 1
a1.append(a)
a1.append(b)
for i in range(n):
c = a + b
a = b
b = c
if len(a1) <= n - 1:
a1.append(c)
print(a1)
print(len(a1))
fib(n)
def pr(a1):
count = 0
for i in a1:
for j in range(2, i):
if i % j == 0:
count += 1
if count > 0:
a2.append()
print(a2)
why the prime number list not working?为什么素数列表不起作用?
I made some fixes to your code:我对您的代码做了一些修复:
def fib(n):
a = 1
b = 2
a1.append(a)
a1.append(b)
for i in range(n):
c=a+b
a=b
b=c
if len(a1)<=n-1:
a1.append(c)
print(a1)
print(len(a1))
def pr(a1):
for i in a1:
isPrime = True
for j in range(2,i):
if i % j == 0:
isPrime = False
break
if isPrime:
a2.append(i)
print(a2)
a1=[]
a2=[]
n=int(input())
fib(n)
pr(a1)
pr()
.pr()
。 It seems a bit, like you are not quite sure how functions work, maybe read a bit into them (or just ask away:) )a
and b
anyway, why not start them of with the correct fibonacci sequence (1, 2,..) to avoid duplicates?a
和b
,为什么不用正确的斐波那契数列 (1, 2,..) 开始它们以避免重复?pr()
you used the append()
method without an argument.pr()
中,您使用了不带参数的append()
方法。 You need to tell the program what you want to append to the list. Hope this helps a bit.希望这个对你有帮助。
Try the below code.试试下面的代码。 Edited your code and a2 will give prime numbers in the fibonacci list.
编辑您的代码,a2 将在斐波那契列表中给出质数。
a1 = []
a2 = []
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
n = 10
if n > 0:
for i in range(n):
a1.append(recur_fibo(i))
for num in a1:
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
a2.append(num)
print(a2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.