program to find fibonacci sequence of a number - python

how do i find the fibonacci sequence of a number . Here Is The code
def fib(n):
for i in range(n):
b = 1
b+=i
print(b)
p = fib(9)
the program just returns the normal sum. how to do this in the easy way

The fibonacci sequence is built by adding the last two values of the sequence, starting with 1,1 (or 0,1 for the modern version). A recursive function does it elegantly:
def fib(n,a=1,b=1):
return a if n==1 else fib(n-1,b,a+b)

n = 10
a, b = 0, 1
while a <= n:
print(a)
a, b = b, a + b

try this using recursion
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

Related

How to write Fibonacci with generator without stop number

I went through Beginning Python fibonacci generator
How to write with out stop number where we want to stop.
My Code of FIbnocci is below
def Fibonnaci(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return (Fibonnaci(n-1)+ Fibonnaci(n-2))
n = int(input())
print(Fibonnaci(n))
I wrote with yield statement but its infinite loop running
def fib(n):
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib(7)
Desired out >
13
You don't want to loop infinitely; you need to keep track of how many times you've performed an operation.
Hold the state of a counter in your loop while you generate elements. Keep going until count >= n.
def fib(n):
count = 0
a, b = 0, 1
while count < n:
yield a
a, b = b, a + b
count += 1
You can then leverage this in a list comprehension to get all of the values up to that Fibonacci number if you so desire.
[i for i in fib(10)]
The yield statement is used to iterate over some data, yielding one value at a time.
So: iterate over it
f = fib()
fibs = [next(f) for _ in range(7)]
fib_7 = fibs[-1]
note as you start with yield a you get a 0 as first number. so shift to yield b which will work as expected
n = int(input())
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b #swap the values, sum
def firstn(g, n):
for i in range(n):
yield g.__next__() # take the next value for the generator
t = (list(firstn(fibonacci(), n+1))) # Put in a list
print (t[-1]) #take the last element

Fibonacci sequence calculator python

Hi I'm fairly new to python and trying to create a Fibonacci calculator function that prints all values up to a given number, if the number entered is not in the sequence then it adds the next Fibonacci number to the list. For example, if 10 is entered it should return [0, 1, 1, 2, 3, 5, 8, 13]. The function has to be recursive. Here is my current code:
def fibonacci(n):
n = int(n)
# The nested sub_fib function computes the Fibonacci sequence
def sub_fib(n):
if n < 2:
return n
else:
return (sub_fib(n-1) + sub_fib(n-2))
#This aspect of the main fib function applies the condition if the number
# input is not in the sequence then it returns the next value up
fib_seq= [sub_fib(i) for i in range(0,n) if sub_fib(i)<=n]
if fib_seq[-1] < n:
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq
else:
return fib_seq
print(fibonacci(input("Input a number to print sequence up to: ")))
I've managed to get it to work but it is incredibly slow (I assume due to the recursion) is there anyway I can speed it up without massively changing the program?
The two main reasons why your program is slow:
you calculate each Fibonacci number separately, you do not reuse the effort you have invested in finding the previous number;
you calculate the first n Fibonacci numbers, but from the moment the condition fails, you can stop.
You can change the program to still be recursive, but reuse the work to compute the previous number, and stop from the moment you have constructed the list.
You simply have to use the following function:
def fibon(a,b,n,result):
c = a+b
result.append(c)
if c < n:
fibon(b,c,n,result)
return result
and we initialize it with: fibon(0,1,n,[]). In each iteration, it will calculate the next Fibonacci number c = a+b and append it to the result. In case that number is still smaller than c < n then we need to calculate the next number and thus perform the recursive call.
def fibonacci(n):
n = int(n)
def fibon(a,b,n,result):
c = a+b
result.append(c)
if c < n:
fibon(b,c,n,result)
return result
return fibon(0,1,n,[])
print(fibonacci(input("Input a number to print sequence up to: ")))
This uses recursion but much faster than naive recursive implementations
def fib(n):
if n == 1:
return [1]
elif n == 2:
return [1, 1]
else:
sub = fib(n - 1)
return sub + [sub[-1] + sub[-2]]
Here are some examples of how you can improve the speed:
"""
Performance calculation for recursion, memoization, tabulation and generator
fib took: 27.052446
mem_fib took: 0.000134
tabular_fib took: 0.000175
yield_fib took: 0.000033
"""
from timeit import timeit
LOOKUP_SIZE = 100
number = 30
lookup = [None] * LOOKUP_SIZE
def fib(n):
return 1 if n <= 2 else fib(n - 1) + fib(n - 2)
def mem_fib(n):
"""Using memoization."""
if n <= 2:
return 1
if lookup[n] is None:
lookup[n] = mem_fib(n - 1) + mem_fib(n - 2)
return lookup[n]
def tabular_fib(n):
"""Using Tabulation."""
results = [1, 1]
for i in range(2, n):
results.append(results[i - 1] + results[i - 2])
return results[-1]
def yield_fib(n):
"""Using generator."""
a = b = 1
yield a
yield b
while n > 2:
n -= 1
a, b = b, a + b
yield b
for f in [fib, mem_fib, tabular_fib, yield_fib]:
t = timeit(stmt=f"f({number})", number=10, globals=globals())
print(f"{f.__name__} took: {t:.6f}")

Least common multiple of n numbers, using recursion

I need to write a recursive function, which finds the least common multiple elements of the list with n length.
My code:
import random
def random_num(n):
return [random.randint(-20,20) for i in range(n)]
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def my_nok(n,m):
return (n/gcd(n,m))*m
The first problem is: my functions work only with two arguments, not with the whole list.
The second problem: i need to have the only one function for finding the least common multiple (my code contains two for that).
You need something to recur through a list, such as the following. If there are 2 elements in the list, do your normal LCM. If it's longer, then recur on the list tail, and then do LCM with that result and the first element.
def lcm(in_list):
if len(in_list) == 2:
# Do your normal LCM computation here
else:
return lcm([in_list[0], lcm(in_list[1:]))
you need to find to LCM of the whole list. let "l" be the LCM of the whole array and if we pick any 2 random numbers from array, they will have a LCM say "l1" and so on and so forth "l2","l3","l4".... the LCM of these will also be the LCM of the whole array.
# we can find LCM of two numbers by the basic prime factorizing method
# but i will use the idea that GCD(a,b) * LCM(a,b) = a*b
# and it is easy to find the GCD(a,b)=[GCD(a,a%b)or GCD(b,b%a)] depending on if a is bigger or b
# i have used this idea because factoring large numbers take time.
so my idea is you can use divide and conquer
def LCM_of_array(array):
if len(array)==2:
return LCM(a,b)
else:
return LCM( LCM_of_array(n[0:len(array)/2]) , LCM_of_array(n[len(array)/2:len(array)])
you can explicitly define LCM(a,b) or just add a few more line of codes in this only
Edit: Code
def nod(a, b): #to find GCD
if b == 0:
return a
else:
if a>b:
return nod(b, a % b)
else:
return nod(a,b%a)
def nok(a, b): #to find LCM of two numbers
return a * b / nod(a, b)
def nok_of_array(n): #function for LCM of array
if len(n) == 2:
return nok(n[0], n[1])
else:
return nok (nok_of_array(n[ 0:len(n)/2 ]) , nok_of_array( n [ len(n)/2 : len(n)]))
My code, the last return doesn't work correct.
import random
def nod(a, b):
if b == 0:
return a
else:
return nod(b, a % b)
def nok(a, b):
return a * b / nod(a, b)
def nok_of_array(n):
if len(n) == 2:
return nok(n[1], n[2])
else:
return nok(nok_of_array[0:len(n)/2], nok_of_array[len(n)/2:len(n)])
n = [random.randint(-20,20) for i in range(0, random.randint(1, 20))]
print(nok_of_array(n))
print(n)
Here is a solution I could work out and it worked for me.
def findDivisor(number):
if number%2 == 0:
return 2
elif number%3==0:
return 3
return number
def LCM(nums):
lcm = 1
while len(nums) > 0:
minOfnums = min(nums)
divisor = findDivisor(minOfnums)
for x in range(0, len(nums)):
Quotient = nums[x]/divisor
Reminder = nums[x]%divisor
if Reminder == 0:
nums[x] = Quotient
lcm*=divisor
minOfnums = min(nums)
if minOfnums == 1:
nums.remove(minOfnums)
return lcm

Finding nth number of primes in Fibonacci sequence (Faster)

I'm taking my first programming course, and my assignment has been to list the nth number of prime numbers in the Fibonacci sequence.
So far I've come up with this:
num = int(input("Enter a number: "))
a = 1
b = 1
c = 0
count = 0
isPrime = True
while (count < num):
isPrime = True
c = a + b
for i in range(2,c):
if (c % i == 0):
isPrime = False
break
if (isPrime):
print (c)
count = count + 1
a = b
b = c
This works, but for any input greater than 10 it takes a really long time, can anyone help me figure out how to make it a bit quicker? I assume it's because a,b and c end up becoming really big, but I'm not sure how to fix this.
fib = lambda n:reduce(lambda x,n:[x[1],x[0]+x[1]], range(n),[0,1])[0]
shortest and fastest fibonacci numbers one liner script in python.
>>> fib(1000)
43466557686937456435688527675040625802564660517371780402481729089536555417949051
89040387984007925516929592259308032263477520968962323987332247116164299644090653
3187938298969649928516003704476137795166849228875L
found here.
It's easiest to separate generation of fibonacci numbers from testing for primality. Here's a Python implementation of the Miller-Rabin primality test:
def isPrime(n, k=5): # miller-rabin
from random import randint
if n < 2: return False
for p in [2,3,5,7,11,13,17,19,23,29]:
if n % p == 0: return n == p
s, d = 0, n-1
while d % 2 == 0:
s, d = s+1, d/2
for i in range(k):
x = pow(randint(2, n-1), d, n)
if x == 1 or x == n-1: continue
for r in range(1, s):
x = (x * x) % n
if x == 1: return False
if x == n-1: break
else: return False
return True
Then it is easy to generate fibonacci numbers and test them for primality:
a, b, f = 1, 1, 2
while True:
if isPrime(f): print f
a, b, f = b, f, b+f
It won't take too long to find the 22nd prime fibonacci number:
357103560641909860720907774139063454445569926582843306794041997476301071102767570483343563518510007800304195444080518562630900027386498933944619210192856768352683468831754423234217978525765921040747291316681576556861490773135214861782877716560879686368266117365351884926393775431925116896322341130075880287169244980698837941931247516010101631704349963583400361910809925847721300802741705519412306522941202429437928826033885416656967971559902743150263252229456298992263008126719589203430407385228230361628494860172129702271172926469500802342608722006420745586297267929052509059154340968348509580552307148642001438470316229
You can see the program in action at http://ideone.com/L1oQgO. See A005478 or A001605 for more.
You definitely should use the following well-known heuristic:
To check if N is a prime number you only need to divide it by the
numbers from 2 to sqrt(N).
#user448810 implicitly uses it in the Miller-Rabin primality test. But just in case you just want to improve upon your own code.
This code does the same as the one line code and is more readable:
def fib(n):
a=1
b=1
for i in range(n-2):
a,b = b,a+b
return b

Fibonacci list how do i make a conditional that excludes a number

fib = [0,1]
a = 1
b = 0
i = 0
while i < n:
i = a+b
a,b = i, a
fib.append(i)
This works in cases where 'n' (which is a given variable) is a number in an actual Fibonacci sequence, like 21 or 13. However, if the number is something like six, it adds one more number than it should. The list should not contain a number that is greater than n.
You could always add a to the list first, then do your incrementing.
fib = [0]
a, b = 1, 0
while a <= n:
fib.append(a)
a,b = a+b, a
Using the classic shnazzy recursive Fibonacci function (which took me a few tries to remember and get right):
def fib(num):
if ((num == 0) or (num == 1)): return 1
fib_num = fib(num - 1) + fib(num - 2)
return fib_num
x, n, i = 2, 15, []
while (fib(x) < n):
i.append(fib(x))
x += 1

Categories