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)
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)
So I was trying this question on g4g:
https://practice.geeksforgeeks.org/problems/sort-the-given-array-after-applying-the-given-equation0304/1#
Here I am using the idea to get the minima/maxima of the quadratic
equation so that I can apply the merge process(which is using two
sorted arrays to make a single sorted array containing both the
elements) Here A0 and A<=0 is used to get the nature of the parabola,
opening upward or downward
I am facing error at out.append(A*arr[i]arr[i]+Barr[i]+C) as
indexerror, list out of range. I am sure if x = 0 or x = len(nums),
then I'll get into trouble, but I am not able to think anything
otherwise:
Some of the test cases are:
A = 1, B = 1, C = 1. N = 3 Arr[] = {1, 2, 3}
A = -1, B = 2, C = -1. N = 6 Arr[] = {-1, 0, 1, 2, 3, 4}
Here is my code for the same:
class Solution:
def sortArray(self, arr, n, A, B, C):
# Code here
#nums = arr[:]
#print(nums)
out = []
nums = []
for i in range(len(arr)):
nums.append(A*arr[i]*arr[i]+B*arr[i]+C)
x = -((B)//2*A)
#print(x)
i = x
j = x-1
#out = []
if i == 0:
return arr
if A>0:
while j>=0 and i<len(nums):
if A*arr[i]*arr[i]+B*arr[i]+C<=A*arr[j]*arr[j]+B*arr[j]+C:
out.append(A*arr[i]*arr[i]+B*arr[i]+C)
i+=1
else:
out.append(A*arr[j]*arr[j]+B*arr[j]+C)
j-=1
while i<len(nums):
#print(i)
out.append(A*arr[i]*arr[i]+B*arr[i]+C)
i+=1
while j>=0:
out.append(A*arr[j]*arr[j]+B*arr[j]+C)
j-=1
return out
elif A<=0:
i = 0
j = len(nums)-1
while j>=x and i<x:
if A*arr[i]*arr[i]+B*arr[i]+C<=A*arr[j]*arr[j]+B*arr[j]+C:
out.append(A*arr[i]*arr[i]+B*arr[i]+C)
i+=1
else:
out.append(A*arr[j]*arr[j]+B*arr[j]+C)
j-=1
while j>=x:
out.append(A*arr[j]*arr[j]+B*arr[j]+C)
j-=1
while i<x:
out.append(A*arr[i]*arr[i]+B*arr[i]+C)
i+=1
return out
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
T=int(input())
for i in range(T):
a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
n = int(input())
arr = list(map(int, input().split()))
ob = Solution()
ans = ob.sortArray(arr, n, a, b, c)
for each in ans:
print(each,end=" ")
print()
#} Driver Code Ends
Thanks in advance!
Always try to break such a problem down into small junks that makes it way easier for you to understand what is happening and find errors. Also, you don't need to define a class for this problem, when you can just use simple functions.
I don't want to give a finished code sample, because I guess you like to solve the problem yourself, so here is a boilerplate that may help you to solve it. The body of the two functions should not be longer than maybe 10 lines of code, so if you end up with more lines, you should reconsider. Good luck :)
def calculate_new_array(arr, a, b, c):
# calculate the resulting array out of the input values
# ...
# return resulting array
return result
def sort_array(arr):
# sort the array somehow
# ...
# return the sorted array
return sorted_arr
if __name__ == '__main__':
a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
arr = list(map(int, input().split()))
new_array = calculate_new_array(arr, a, b, c)
sorted_array = sort_array(new_array)
print(sorted_array)
Small little spoiler: With python N is not that important.
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 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
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)