m = 2
n =20
a,b = m,0
fib = [m]
while a <= n:
fib.append(a)
a,b = a+b, a
So given two variables from m to n (and m < n), I need to create a list containing all the numbers of the Fibonacci sequence between m and n inclusive (but cannot exceed) ex: if m = 2 and n = 20 then fib should be [2,3,5,8,13].
I do not know how to start the fibonnaci sequence midway, so the best I can think of is to filter the results afterwards.
def f(low, high):
fib = [0]
a, b = 1, 0
while a <= n:
fib.append(a)
a,b = a+b, a
return filter(lambda x: x >= low and x =< high, fib)
The fibonacci code is trivial, the new thing you might be seeing here is filter, which takes a function f and an iterable x, and returns a new iterable with all of the elements from x such that f(x) is true.
def fib(m,n):
a,b = 1,1
while a < m:
a,b = b, a+b
answer = [a]
while b < n:
a,b = b, a+b
answer.append(a)
return answer
In [2040]: fib(2,20)
Out[2040]: [2, 3, 5, 8, 13]
m = int(raw_input("Enter the start number : "))
n = int(raw_input("Enter the end number : "))
def fib(i):
if i == 0: return 0
elif i == 1: return 1
else: return f(i-1)+f(i-2)
print map(fib, range(m, n))
I hope this is what you need.
I thanks it's simple and clear to calculate the Fibonacci number recursively or by put all the number in a list. But if the number is too large, it not a good idea.
Here is code ,BTW
def main():
print fibo(100,600)
def fibo(m,n):
f0=2
f1=3
while f1<m:
tmp=f1
f1=f0+f1
f0=tmp
res=[f0]
while f1<n:
res.append(f1)
f1=res[-2]+res[-1]
return res[1:];
if __name__ == '__main__':
main()
I googled and find the n-th term formula of fibonacci here
so the codes could be:
def fibn(n):
Phi = (1+math.sqrt(5))/2
phi = (1-math.sqrt(5))/2
return round((math.pow(Phi, n) - math.pow(phi, n))/math.sqrt(5))
>>> fibn(0)
0.0
>>> fibn(1)
1.0
>>> fibn(2)
1.0
>>> fibn(3)
2.0
>>> fibn(4)
3.0
>>> fibn(5)
5.0
>>> fibn(6)
8.0
>>> fibn(7)
13.0
>>> fibn(8)
21.0
>>> fibn(9)
34.0
>>> fibn(10)
55.0
You could do something like:
def fibs(low,high):
a, b = 0, 1
while 1:
a, b = b, a+b
if low <= a:
if a <= high:
yield a
else:
break
you can use it like
>>> for num in fibs(2,15):
... print num
...
2
3
5
8
13
But without resorting to the formula for the nth Fibonacci number and relying on proper rounding there isn't a way of getting the nth number without computing the first n-1 numbers.
So, if you don't want to use the formula it would probably be best to just keep a list of the Fibonacci numbers around and use that, if it turns out you need numbers between low and high where high > fib_nums[-1] then you can always use fib_nums[-1] and fib_nums[-2] as b and a to compute the values you're missing.
There are a few subproblems to consider for getting a log order solution, assuming (n-m) is relatively small. If (n-m) can be relatively large its best to precompute all reults and simply do a binary search.
Can we find i th fibonacci number in log time?
Can we find the number j such that fib(j) >= m ?
For first problem we can find i th fibonacci using (http://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form).
And the second problem can be solved using a binary search and uses first method to find the fibonacci number >= m. Once we know j we can find j+1 th fibonacci number in log time, and simply generate all other numbers <=n using these.
Using Generator :
import os,sys
def fib(num):
a=0
b=1
while 1:
a,b =b, b+a
yield a
low=2
high=200
for i in fib(range(1)):
if i <= high and i >= low :
print i
elif i > high:
break
O/P
2
3
5
8
13
21
34
55
89
144
Related
Trying to write a piece of code that will sum the digits of a number. Also I should add that I want the program to keep summing the digits until the sum is only 1 digit.
For example, if you start with 1969, it should first add 1+9+6+9 to get 25. Since the value 25 has more than a single digit, it should repeat the operation to obtain 7 as a final answer.
Was just wondering how I could pull this off and possibly make it recursive as well. This is what I have so far
def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
Convert back and forth between strings and ints, make use of sum().
>>> def foo(n):
n = str(n)
if len(n) == 1:
return int(n)
return foo(sum(int(c) for c in n))
>>> foo(1969)
7
>>>
def foo(n):
n = str(n)
if len(n) == 1:
return int(n)
return foo(sum(int(c) for c in n))
It is as simple as involving explicitly the recursion.
def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n // 10
if len(str(r))>1:
return sum_digits3(r)
return r
But i must admit that i am going to read the links given by suspicious dog. And the answer of wwii is smarter than mine.
I have two numbers say A = 10 and B =20.
Now I need to count the palindrome numbers in Range (A,B)
I tried this:
s = list(map(int,raw_input().split()))
a = s[0]
b = s[1]
l = range(s[0],s[1]+1)
# print "list : ",l
def isNumberPalindrome(n):
return str(n) == str(n)[::-1]
x = filter(isNumberPalindrome, l)
# print " All Palindorme numbers : ",x
count = len(x)
print count
I have problem of memory exceeding if A and B are in range of 10^18.
Can somebody suggest me how to solve this.
Thanks in Advance
Use a generator instead of calling range().
from __future__ import print_function
def isNumberPalindrome(n):
return str(n) == str(n)[::-1]
a = pow(10, 18)
b = pow(10, 19) + 1
def gen_range(start, end):
i = long(start)
while i < end:
yield i
i = i + 1
count = 0
for l in gen_range(a, b):
count += isNumberPalindrome(l)
print(count)
It is not the whole answer. But consider this:
For range 10^n to 10^n+1 you can find the number of palindromes in constant time. It is 10^ceil(n/2) - 10^ceil(n/2)-1. Because (for example) for n = 6 and range from 10^6 to 10^7 (1 000 000 - 10 000 000) number of palindromes is the number of possible numbers from 1000 to 10000 (that represent the first half of original numbers. 4315 is the first half of 4315134 and so on).
So you don't filter numbers but find how many palindromes you can generate in such range.
I was writing code for finding sum of even-valued terms in Fibonacci sequence whose values do not exceed four million.the code works fine for values upto 40k But I got an memory error for finding upto 4 million can someone help me resolve the problem
my code is:
def fib(x):
l=[0,1]
m=[]
a=0
c=0
b=1
while len(l) <=x:
d=c+b
c=b
b=d
l.append(d)
if d%2==0:
m.append(d)
a=a+d
print
print a
print m
Just to clarify as I understand: You are looking for a function which returns the sum of all the even numbers in the fibonacci sequence, up to 4 million. Try it with two separate functions like this.
The first function for a given number in the fibonacci sequence:
def fib(n):
a = 0
b = 1
for e in range(n):
old_a = a
a = b
b = old_a + b
return a
The second function for the sum which calls the earlier function (and uses a count, not a list, so as to save on memory.):
def even_sum(t):
total = 0
for x in range(t):
fib_x = fib(x)
if fib_x % 2 == 0:
total += fib_x
print fib_x # <-- this line is optional,
# include it if you want to see each
# even number printed.
return total
Then call your function. For example:
print even_sum(100)
which gives us this answer:
286573922006908542050
try this:
def sum_fib(x):
a = 0
c = 0
b = 1
l = 2
while l <=x:
d = c + b
c = b
b = d
l += 1
# yoda conditions check
if 0 == d % 2: # using binary should be faster (0 == d & 1)
a += d
print
print a
As said in the comments replace l with a counter. If you need to print all the even fib numbers keep m otherwise remove it all together.
Initialize count
count = 2
And every time around the while loop increment count by 1.
Here's a version that eliminates the unnecessary lists, as I described in my comments. Note that you are still going to have an exponentially-growing sum, which is unavoidable:
def fib(x):
lc=2
mc=0
a=0
c=0
b=1
while lc <=x:
d=c+b
c=b
b=d
lc += 1
if d%2==0:
mc += 1
a += d
print
print a
print mc
I am trying to solve the following using Python:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
So far, I have been able to generate the Fibonacci elements but in trying to sum the even elements, my code seems to stall. Here is the code below:
def fib(n):
if n==0:
return 0
elif n==1:
return 1
if n>1:
return fib(n-1)+fib(n-2)
n=0
total=0
while fib(n)<=4000000:
if fib(n)%2==0:
total+=fib(n)
print(total)
Any suggestions would be welcome.
You have an infinite loop as n isn't ever incremented up from zero in your while loop. Additionally, why not sum your Fibonacci total as well as find the next Fibonacci value in the same while loop, like this:
x= 1
y=1
total = 0
while x <= 4000000:
if x % 2 == 0:
total += x
x, y = y, x + y
print (total)
Outputs:
4613732
since this looks like a homework assignment, I threw in some interesting Python
from math import sqrt
# Using Binet's formula
def fib(n):
return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))
def sum_even_terms(limit = 4000000):
n = total = 0
while True:
term = fib(n)
n += 1
if term > limit: break
if term % 2 == 0:
total += term
return total
print sum_even_terms()
def is_nth_term_even(n):
return (fib(n) % 2 == 0)
print is_nth_term_even(30)
Just for fun, here's a really short solution:
def fib_even_sum(limit=4*10**6):
"""Sum of the even Fibonacci numbers up to the given limit."""
b, c = 1, 2
while c <= limit:
a = b + c; b = c + a; c = a + b
return b // 2
print fib_even_sum() # outputs 4613732
It's based on the following facts:
Every third Fibonacci number is even.
If Fib(n) is even, then the sum of the even Fibonacci numbers up to Fib(n) is equal to the sum of the odd Fibonacci numbers up to Fib(n) (because each even Fibonacci number is the sum of the two preceding odd Fibonacci numbers).
The sum of all Fibonacci numbers (even and odd) up to and including Fib(n) is Fib(n+2) - 1 (via an easy proof by induction).
So if Fib(n) is the last even number to be included in the sum, then
the total you want is just (Fib(n+2) - 1) / 2.
You can also use a generator and add the numbers
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
f = fib()
total = 0
while total <= 4000000:
current = f.next()
if current % 2 == 0:
total += current
print total
I am attempting to do Project Euler problem #2. Which is:
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
However the terminal window hangs when I use the following code with 4000000. Smaller numbers run ok. Is there something about this code that is really inefficient, hence the lagginess?
n = int(raw_input("Enter the start number: "))
def fib_generator():
a, b = 0, 1
yield 0
while True:
a, b = b, a + b
yield a
def even_sum(fib_seq):
seq = []
seq = [next(fib_seq) for number in range(n)]
seq = [number for number in seq if number % 2 == 0]
return sum(seq)
def start():
fib = fib_generator()
even_sum = even_sum(fib)
print even_sum
start()
You have a bug. You're generating the first 4,000,000 Fibonacci numbers, but the problem statement only asks for those Fibonacci numbers whose values are not more than 4,000,000.
Since the Fibonacci numbers grow exponentially (Fn ~ 1.618n), you're generating some numbers with a very large number of digits (log10 Fn ~ n / 5) and that will take an immense amount of time.
Fix the bug, and you'll be okay.
You just need to add logic to stop when the next fibonacci number exceeds 4000000.
Also, I spy a potential problem with this line:
def start():
fib = fib_generator()
even_sum = even_sum(fib) #<--- right here
print even_sum
It isn't good to have a variable name the same as the function name.
Yes, there is something inefficient in your code, you load a very long list into memory twice, with your two seq = ... statements. Why not try one generator expression rather than two list comprehensions? Also, you could alter your Fibonacci generator to stop at a certain number:
def fib_generator(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
def even_sum(fib_seq):
seq = (number for number in fib_seq if not number % 2)
return sum(seq)
def start():
n = int(raw_input('Enter max constraint: '))
fib_seq = fib_generator(n)
even_sum1 = even_sum(fib_seq)
print even_sum1
start()
This ran pretty fast for me
lst = []
num1 = 1
num2 = 2
sum = 0
jump = 0
next = 0
while next<4000000:
next = num1 + num2
if next<4000000:
if jump ==0:
num1 = next
jump = 1
else:
num2 = next
jump = 0
if next%2 == 0:
lst.append(next)
for item in lst:
sum+=item
print ''
print "Sum: ",
print sum