I wrote a Fibonacci series using Python. Could not figure out why second program is giving wrong answer and first one right when both look same.
Below program gives right answer
def fib(n):
a,b=0,1
while b<n:
print b
a,b=b,a+b
fib(4)
1
1
2
3
Below program gives wrong answer:
def fib(n):
a = 0
b = 1
while b<n:
print b
a = b
b = a+b
fib(4)
1
2
In first one, a, b = b, a+b does the assigning simultanously.
In second one, you are first doing a = b and then doing b = a+b which actually is just b = 2*b.
How to achieve such behaviour in second one? Use temporary value to store a.
def fib(n):
a = 0
b = 1
while b<n:
print b
temp = a
a = b
b = temp+b
fib(4)
>>>1
>>>1
>>>2
>>>3
In the second code posted, you redefine the value of b after having changed a, resulting as
def fib(n):
a = 0
b = 1
while b<n:
print b #prints 1
a = b #a = 1
b = a+b #b = 1 + 1 = 2
In the second code, there is no problem, as python code generally reads equations from right to left, thus redefines b first, as is correct
def fib(n):
a,b=0,1 #a = 0, b = 1
while b<n:
print b
a,b=b,a+b #b = 0 + 1 = 1, #a = 1
fibonacci series using lambda function in python
n = int(input("Enter the range of numbers in fibonacci series:"))
F = [0,1]
list(map(lambda i: F.append(F[i-1] + F[i-2]), range(2, n)))
print(F)
fibonacci series using List Comprehension function in python
n = int(input("Enter the range of numbers in fibonacci series:"))
F = [0,1]
[F.append(F[i-1] + F[i-2]) for i in range(2,n)]
print(F)
In the first example, you've used this code:
a,b=b,a+b
While in the second, you've done this instead:
a = b
b = a+b
These are not the same thing.
For the sake of argument, let's say that a = 3 and b = 6. Let's run the working code first:
>>> a, b = 10, a + 1
>>> a
10
>>> b
4
The value of a + 1 is 4 rather than 11, because b's assignment is using the old value of a, so 3 + 1 == 4.
Now let's put a and b back to their starting values. Let's try the other method of assigning:
>>> a = 10
>>> b = a + 1
>>> a
10
>>> b
11
Now b is 11! That's because a was assigned before the assignment of b, so the addition uses a's new value.
The reason your second version isn't working is because the assignments don't happen simultaneously, so b is actually 2 * b because a has already been set to b by the time a+b is executed.
def fibonacci (n):
if n == 1 or n == 2:
return 1
return fibonacci (n-1) + fibonacci (n-2)
for i in range(1,50):
print (fibonacci(i))
n1 = 0
n2 = 1
c = 0
nTerms = int(input())
if nTerms <= 0:
print("Enter the valid value")
elif nTerms == 1:
print(a)
else:
while c < nTerms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
c += 1
Fibonacci Series Using Recursion
def f_recursion(n):
if n <= 1:
return n
else:
return(f_recursion(n-1) + f_recursion(n-2))
# Driver Code
nterms = int(input())
if nterms <= 0:
print("Enter the positive value")
else:
for i in range(0,nterms):
print (f_recursion(i))
n1=int(input("Enter Term"))
mylist=[0,1]
for a in range(n1):
sum=0
for b in mylist[len(mylist)-2:]:
sum+=b
mylist.append(sum)
print(mylist)
def fib(n):
a=0
b=1
sum=0
for i in range(0,n):
print(sum)
sum = a + b
b = a
a = sum
fib(10) // here you can add any n value from 1 to 100
# The below code will generate the fibonacci series as per desired range
# just put the number, you want the fibonaci series upto.
def fibonacci(num):
x,y = 0,1
if num==1:
print(x)
elif num==2:
print(x,y)
else:
print(x,y,end = " ")
for i in range(num-2):
z=x+y
x=y
y=z
print(z,end = " ")
def fib(n1, n2):
print(n1)
print(n2)
for i in range(n1, n2):
n1 += n2
n2 += n1
print(n1)
print(n2)
starting_number = int(input('Enter First Term: '))
ending_number = int(input('Enter Second Number: '))
fib(starting_number, ending_number)
Related
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)
problem:
For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum().
------------------------------------------------------------------------
round_sum(16, 17, 18) → 60
round_sum(12, 13, 14) → 30
round_sum(6, 4, 4) → 10
my code:
def round_sum(a, b, c):
round10(a)
round10(b)
round10(c)
return a+b+c
def round10(num):
if num%10>=5:
while num%10!=0:
num = num+1
else:
while num%10!=0:
num = num-1
enter link description here
You don't modify a,b,c. round10 computes the value you want but since you don't keep it in any variable it's forgotten immediately. Try this:
def round_sum(a, b, c):
a = round10(a)
b = round10(b)
c = round10(c)
return a+b+c
also round10 needs to return your final value:
def round10(num):
if num%10>=5:
while num%10!=0:
num = num+1
else:
while num%10!=0:
num = num-1
return num # <----
My Code
def round_sum(a, b, c):
count = 0
for i in (a,b,c):
if i<5: i = 0
if i>4 and i<10: i = 10
if i%10 in [5,6,7,8,9]and i!= 0 and i > 9:
i = i + (10-i%10)
elif i%10 in [1,2,3,4] and i!=0 and i > 9:
i = i - (i%10)
count = count + i
return count
def roundsum(a, b, c):
sum=0
for x in (a,b,c):
if 5<=x<=10:
y=x-x+10
sum+=y
elif x>10:
if x%10<5:
y=x-(x%10)
sum+=y
elif x%10>=5:
y=x-(x%10)+10
sum+=y
return sum
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
I have a problem about making a fibonacci sequence to a list, I'm just new to python someone help me please.
This is my code. I know this is looking wrong or something because it says invalid syntax. I don't know what to do about this really :(
This code works for a normal code without using a list!
myArray1 = [0]
myArray2 = [1]
while myArray2 < 700:
myArray1, myArray2 = b[i], myArray1+myArray2[i]
print(myArray2)
This code puts the first 700 fibonacci numbers in a list. Using meaningful variable names helps improve readability!
fibonacci_numbers = [0, 1]
for i in range(2,700):
fibonacci_numbers.append(fibonacci_numbers[i-1]+fibonacci_numbers[i-2])
Note: If you're using Python < 3, use xrange instead of range.
You may want this:
In [77]: a = 0
...: b = 1
...: while b < 700:
...: a, b = b, a+b
...: print a, b
1 1
1 2
2 3
3 5
5 8
8 13
13 21
21 34
34 55
55 89
89 144
144 233
233 377
377 610
610 987
If you wanna store the results in a list, use list.append:
In [81]: a = 0
...: b = 1
...: fibo=[a, b]
...: while b < 70:
...: a, b = b, a+b
...: fibo.append(b)
...: print fibo
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
There are two kinds of mistakes you are making; mistakes that are creating errors and mistakes that are affecting readability
Both instances of the phrase [i] should be removed. I believe that you may be thinking it has something to do with iteration or tuples, but that is part of the reason you are getting errors:
myArray1 = [0]
myArray2 = [1]
while myArray2 < 700:
myArray1, myArray2 = b, myArray1+myArray2
print(myArray2)
the other part of the reason you are getting errors is because of the variable b. You don't declare it and it does not belong. This code will iterate correctly if you switch out b with myArray2:
myArray1 = [0]
myArray2 = [1]
while myArray2 < 700:
myArray1, myArray2 = myArray2, myArray1+myArray2
print(myArray2)
then there are some legibility issues. I would change the phrase myArray1 and 2 to a and b respectively. First because it is just too long; second because in python it is called lists, not arrays; third because you are referring to integers, not lists or arrays:
a = [0]
b = [1]
while b < 700:
a, b = b, a+b
print(b)
then, the variables that were myArray1 and 2, but are now a and b; those are integers and they do not need to be expressed as single object lists. so get rid of the brackets around them:
a = 0
b = 1
while b < 700:
a, b = b, a+b
print(b)
Then, the last phrase in this code says print(b). If you have it printing b then the fibonacci sequence you get is missing its first 1. It will read (on separate lines of course) 1,2,3,5,8,13 and so on. It should read 1,1,2,3,5,8,13. You are missing the first 1. So print(b) needs to be changed to print(a):
a = 0
b = 1
while b < 700:
a, b = b, a+b
print(a)
then, if you are expressing more than one variable you can just list all the variables separated by commas equal to all the values separated by commas like this:
a,b,c,d = 1,2,3,4
so for your code that would translate to:
a,b = 0,1
while b < 700:
a, b = b, a+b
print(a)
then get rid of that extra space, white space means something in python, though here it doesn't really make a difference:
a,b = 0,1
while b < 700:
a, b = b, a+b
print(a)
So all of this so far has just been enough to get you to your original problem: you are getting an iteration (each consecutive value on a seperate line). Below is how you can get a list to any number n:
def fibo(n):
fibo_list = []
a,b = 0,1
while b < n:
a,b = b,a+b
fibo_list.append(a)
print(fibo_list)
hope that helps
def fibonacci(number: int) -> int:
"""
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(3)
2
>>> fibonacci(4)
3
>>> fibonacci(5)
5
>>> fibonacci(6)
8
>>> fibonacci(7)
13
>>> fibonacci(8)
21
"""
fibs = [0] * (number + 2)
fibs[0] = 0
fibs[1] = 1
for i in range(2, number + 1):
fibs[i] = fibs[i - 1] + fibs[i - 2]
return fibs[number]
if __name__ == "__main__":
from doctest import testmod
testmod()
def fibonacci(n, results):
if n == 0:
return 0
elif n == 1:
return 1
else :
f = fibonacci(n-1, results) + fibonacci(n-2, results)
f1 = f[:]
results.appned(f1)
return results
You can use below code, your problem can be solve in just one line.
what are we doing is appending the
fib_nums
till your given limit i.e.,
700
and then adding the
fib_nums
with the second list which is of zero length which explicitly we doing, because it is containing
None
values, that we don't required.
#defining variable
fib_nums = [0, 1]
#just one line code
fib_nums = fib_nums + [fib_nums.append(fib_nums[i-1]+fib_nums[i-2]) for i in range(2,700)]*0
#printing the series
print (fib_nums)
It is not fast but it works as well:
def fibonacci(n):
# return a list of fibonacci numbers
if n == 0:
fibonacci_list = []
elif n == 1:
fibonacci_list = [0]
elif n == 2:
fibonacci_list = [0, 1]
elif n > 2:
fibonacci_list = [0, 1]
for i in range(n-2):
fibonacci_list += [0]
fibonacci_list[-1] = fibonacci_list[-2] + fibonacci_list[-3]
return fibonacci_list
I need to make a program that asks for the amount of Fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I can't get it to work. My code looks the following:
a = int(raw_input('Give amount: '))
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
a = fib()
a.next()
0
for i in range(a):
print a.next(),
I would use this method:
Python 2
a = int(raw_input('Give amount: '))
def fib(n):
a, b = 0, 1
for _ in xrange(n):
yield a
a, b = b, a + b
print list(fib(a))
Python 3
a = int(input('Give amount: '))
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))
You are giving a too many meanings:
a = int(raw_input('Give amount: '))
vs.
a = fib()
You won't run into the problem (as often) if you give your variables more descriptive names (3 different uses of the name a in 10 lines of code!):
amount = int(raw_input('Give amount: '))
and change range(a) to range(amount).
Since you are writing a generator, why not use two yields, to save doing the extra shuffle?
import itertools as it
num_iterations = int(raw_input('How many? '))
def fib():
a,b = 0,1
while True:
yield a
b = a+b
yield b
a = a+b
for x in it.islice(fib(), num_iterations):
print x
.....
Really simple with generator:
def fin(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
ln = int(input('How long? '))
print(list(fin(ln))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...]
Python is a dynamically typed language. the type of a variable is determined at runtime and it can vary as the execution is in progress.
Here at first, you have declared a to hold an integer type and later you have assigned a function to it and so its type now became a function.
you are trying to apply 'a' as an argument to range() function which expects an int arg but you have in effect provided a function variable as argument.
the corrected code should be
a = int(raw_input('Give amount: '))
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
b = fib()
b.next()
for i in range(a):
print b.next(),
this will work
def fibonacci(n):
fn = [0, 1,]
for i in range(2, n):
fn.append(fn[i-1] + fn[i-2])
return fn
To get the fibonacci numbers till any number (100 in this case) with generator, you can do this.
def getFibonacci():
a, b = 0, 1
while True:
yield b
b = a + b
a = b - a
for num in getFibonacci():
if num > 100:
break
print(num)
def genFibanocciSeries():
a=0
b=1
for x in range(1,10):
yield a
a,b = b, a+b
for fib_series in genFibanocciSeries():
print(fib_series)
Your a is a global name so-to-say.
a = int(raw_input('Give amount: '))
Whenever Python sees an a, it thinks you are talking about the above one. Calling it something else (elsewhere or here) should help.
Also you can use enumerate infinite generator:
for i,f in enumerate(fib()):
print i, f
if i>=n: break
Also you can try the closed form solution (no guarantees for very large values of n due to rounding/overflow errors):
root5 = pow(5, 0.5)
ratio = (1 + root5)/2
def fib(n):
return int((pow(ratio, n) - pow(1 - ratio, n))/root5)
You had the right idea and a very elegant solution, all you need to do fix is your swapping and adding statement of a and b. Your yield statement should go after your swap as well
a, b = b, a + b #### should be a,b = a+b,a #####
`###yield a`
Simple way to print Fibonacci series till n number
def Fib(n):
i=a=0
b=1
while i<n:
print (a)
i=i+1
c=a+b
a=b
b=c
Fib(input("Please Enter the number to get fibonacci series of the Number : "))
a = 3 #raw_input
def fib_gen():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
fs = fib_gen()
next(fs)
for i in range(a):
print (next(fs))
I've build this a while ago:
a = int(raw_input('Give amount: '))
fab = [0, 1, 1]
def fab_gen():
while True:
fab.append(fab[-1] + fab[-2])
yield fab[-4]
fg = fab_gen()
for i in range(a): print(fg.next())
No that fab will grow over time, so it isn't a perfect solution.
It looks like you are using the a twice. Try changing that to a different variable name.
The following seems to be working great for me.
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
f = fib()
for x in range(100):
print(f.next())
i like this version:
array = [0,1]
for i in range(20):
x = array[0]+array[1]
print(x)
array[0] = array[1]
array[1] = x
Below are two solution for fiboncci generation:
def fib_generator(num):
'''
this will works as generator function and take yield into account.
'''
assert num > 0
a, b = 1, 1
while num > 0:
yield a
a, b = b, a+b
num -= 1
times = int(input('Enter the number for fib generaton: '))
fib_gen = fib_generator(times)
while(times > 0):
print(next(fib_gen))
times = times - 1
def fib_series(num):
'''
it collects entires series and then print it.
'''
assert num > 0
series = []
a, b = 1, 1
while num > 0:
series.append(a)
a, b = b, a+b
num -= 1
print(series)
times = int(input('Enter the number for fib generaton: '))
fib_series(times)
Why do you go for complex here is one of my snippet to work on!!
n = int(input('Enter your number..: '))
a = 0
b = 1
c = 0
print(a)
print(b)
for i in range(3, n+1):
c = a+b
print(c)
a,b=b,c
check out my git - rohith-sreedharan
We can use it in a short way without through 'yield and 'next' statements
def fib(n):
return n if n <= 1 else fib(n - 1) + fib(n - 2)