Below is my code to make a prime number list from Fibonacci list, but the prime list is not working.
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()
. 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?pr()
you used the append()
method without an argument. You need to tell the program what you want to append to the list. As far as I can tell this is, where you got an exception.Hope this helps a bit.
Try the below code. Edited your code and a2 will give prime numbers in the fibonacci list.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.