Anyone know the most efficient way of displaying the first 100 numbers in the Fibonacci Sequence in Python please?
Here is my current code:
fib1,fib2,fib3= 0,0,1
while fib3< 100:
print(fib3)
fib1=fib2
fib2=fib3
fib3=fib1 + fib2
Understand the working of python and fibonacci Sequence. Use generator feature of python. Follow the code
a = int(input('Give num: '))
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
According to the Fibonacci formula, here's a way to get the nth member of the Fibonacci sequence.
This function doesn't use loops nor recursion (recursions are horrible in Python, they are always slower than an iterative solution, because of how Python handle recursion, see here for more info about it)
Related
I'm trying to write a program to find sum of first N natural numbers i.e. 1 + 2 + 3 + .. + N modulo 1000000009
I know this can be done by using the formula N * (N+1) / 2 but I'm trying to find a sort of recursive function to calculate the sum.
I tried searching the web, but I didn't get any solution to this.
Actually, the problem here is that the number N can have upto 100000 digits.
So, here is what I've tried until now.
First I tried splitting the number into parts each of length 9, then convert them into integers so that I can perform arithmetic operations using the operators for integers.
For example, the number 52562372318723712 will be split into 52562372 & 318723712.
But I didn't find a way to manipulate these numbers.
Then again I tried to write a function as follows:
def find_sum(n):
# n is a string
if len(n) == 1:
# use the formula if single digit
return int(int(n[0]) * (int(n[0]) + 1) / 2)
# I'm not sure what to return here
# I'm expecting some manipulation with n[0]
# and a recursive call to the function itself
# I've also not used modulo here just for testing with smaller numbers
# I'll add it once I find a solution to this
return int(n[0]) * something + find_sum(n[1:])
I'm not able to find the something here.
Can this be solved like this?
or is there any other method to do so?
NOTE: I prefer a solution similar to the above function because I want to modify this function to meet my other requirements which I want to try myself before asking here. But if it is not possible, any other solution will also be helpful.
Please give me any hint to solve it.
Your best bet is to just use the N*(N+1)/2 formula -- but using it mod p. The only tricky part is to interpret division by 2 -- this had to be the inverse of 2 mod p. For p prime (or simply for p odd) this is very easy to compute: it is just (p+1)//2.
Thus:
def find_sum(n,p):
two_inv = (p+1)//2 #inverse of 2, mod p
return ((n%p)*((n+1)%p)*two_inv)%p
For example:
>>> find_sum(10000000,1000000009)
4550000
>>> sum(range(1,10000001))%1000000009
4550000
Note that the above function will fail if you pass an even number for p.
On Edit as #user11908059 observed, it is possible to dispense with multiplication by the modular inverse of 2. As an added benefit, this approach no longer depends on the modulus being odd:
def find_sum2(n,k):
if n % 2 == 0:
a,b = (n//2) % k, (n+1) % k
else:
a,b = n % k, ((n+1)//2) % k
return (a*b) % k
I'm trying to decipher the following homework question. My code is supposed to evaluate to 190 but instead evaluates to 114. So, I don't think I'm understanding the coding requirement.
The Collatz conjecture is an example of a simple computational process
whose behavior is so unpredictable that the world's best
mathematicians still don't understand it.
Consider the simple function f(n) (as defined in the Wikipedia page
above) that takes an integer n and divides it by two if n is even and
multiplies n by 3 and then adds one to the result if n is odd. The
conjecture involves studying the value of expressions of the form
f(f(f(...f(f(n))))) as the number of calls to the function f
increases. The conjecture is that, for any non-negative integer n,
repeated application of f to n yields a sequence of integers that
always includes 1.
Your task for this question is to implement the Collatz function f in
Python. The key to your implementation is to build a test that
determines whether n is even or odd by checking whether the remainder
when n is divided by 2 is either zero or one. Hint: You can compute
this remainder in Python using the remainder opertor % via the
expression n % 2. Note you will also need to use integer division //
when computing f.
Once you have implemented f, test the your implementation on the
expression f(f(f(f(f(f(f(674))))))). This expression should evaluate
to 190.
from __future__ import division
def collatz(n):
l = []
l.append(n)
while n != 1:
if n % 2 == 0:
n = n // 2
l.append(n)
else:
n = (3*n) + 1
l.append(n)
return l
print len(collatz(674))
You just misread the intermediary question. Your programs tries to answer the bigger question... This is what should return 190:
def f(n):
return n // 2 if n % 2 == 0 else 3*n + 1
print f(f(f(f(f(f(f(674)))))))
Like if i told the program n=10, how would I make it return 10*9*8*7*6*5....1?
I thought a while loop but I feel I messed up somewhere because it doesn't sum up all of the numbers in the sequence.
My current code looks like this
def product(n):
i=n
a=n-1
while a>0:
return i * a
b=i * a
a=a-1
i=i-1
Are there any better ways to do it without using recursion? Sorry for the incredibly beginner question, but I'm trying to teach myself how to code. You gotta start somewhere!
Thanks!
Since you are trying to learn to code, I won't give you a total solution, but
I'll give you a few hints instead:
Have a for loop that runs up from 1 to n (using range(1, n+1)) instead of your while-loop. This will generate the values that you want to multiply and iterate the right number of times (which can be a bit tricky with while loops sometimes).
Have a variable named product to store the result of the multiplications each time through the loop.
Initialize product before you enter the for-loop. Once inside you'll be just updating the value of product.
After you are done with the loop, you can use the return statement to return the value of product.
Finally, for testing purposes, you may want to start out with a small value of n, like 4, and print out the values you are computing inside the loop to verify how your code is working.
There are more terse and pythonic ways to do this, but this uses the code structure you have already set up. And of course recursively as well as you mention too.
Once you master the basics, you'll appreciate the more idiomatic ways of writing this, or calling the appropriate functions that do this for you.
Well, here's another Pythonic approach.
>>> import operator
>>> numbers = range(1, 11)
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> reduce(operator.mul, numbers)
3628800
Assuming you what you meant is factorial function, you can simply just use the math.factorial():
>>> import math
>>> math.factorial(10)
3628800
You are trying to find the factorial of a number n, essentially. For finding the factorial of a number, there are 2 methods
Using a Loop structure
Using Recursion (as you've mentioned)
As a new programmer, you would be better off with a simple loop structure that runs from 1 to n and puts the multiplied value at each iteration into a variable. That variable is your answer. But also know that recursion will also work and make the code look elegant. Happy Programming !
This is called the factorial. 10! is equivalent to 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
def factorial(n):
product = 1
while n > 0:
product *= n
n -= 1
return product
By the way, in practice, just use math.factorial.
def factorial(n):
if n <= 1: return 1
return n * factorial(n-1)
I always think of factorial as the quintessential example in learning recursion ...
Another way to do this is to use scipy.product.
>>> import scipy
>>> scipy.product(xrange(1,11))
3628800
As a learner you should do it without using any inbuilt functions it will help you to learn programming rather just tool as learning a tool is much easier one you become good programmer. there are two ways of doing this I have implemented simpler versions.
Using Recursion:
def product(n):
if n== 1:
return 1
return n * product(n-1)
Using Simple Loop:
def product(n):
res = 1
while n>1:
res = res * n
n = n - 1
return res
For factorials too large to compute directly, there is another way to do that by using the Stirling's approximation.
n! := sqrt(2πn)*(n/e)^n, where e = 2.71828
I found this task here.
Given the ith (1<=i<=35) Fibonacci
number F(i) calculate the sum of the
ith till i+9th number
F(i)+F(i+1)+...+F(i+9) and the last
digit of the i+246th one F(i+246)
I have been trying to solve this using python and some tricks(Binnet's formula and a tricky recurrence):
f=lambda n:((1+5**.5)**n-(1-5**.5)**n)/(2**n*5**.5)
exec"n=input();print int(55*f(n)+88*f(n+1)+f(n+6)%10);"*input()
but I didn't yet managed to squeeze thought the give source code limit which is 111 and mine is 115,any hints how to improve my solution?
I am a rather newbie to python so any sort of help resulting in a successful solution will be much appreciated.
Thanks,
Did you try to use this sum formula?
http://en.wikipedia.org/wiki/Fibonacci_number#Second_identity ("Second Identity")?
f = lambda n,t=5**.5:((1+t)**n-(1-t)**n)/(2**n*t) etc. spends 8 characters ,t=5**.5 to gain 12: three lots of 5**.5 -> t. That's a saving of 4 characters, which seems to be what you require.
[EDITED to correct a typo; I had 2*n instead of 2**n in the denominator.]
You can save a few more characters with a different twist on Binet's formula: f=lambda n:round((1+5**.5)**n/5**.5/2**n).
Here is the 110 solution, I had to rewrite the formula though and used #Gareth's suggestion:
p=5**.5
f=lambda n:((1+p)**n-(1-p)**n)/(2**n*p)
exec "n=input();print int(f(n+11)-f(n+1)+f(n+6)%10);"*input()
Saving another symbol, 109 now (manipulating with n and getting rid of +11):
p=5**.5
f=lambda n:((1+p)**n-(1-p)**n)/(2**n*p)
exec "n=input()+6;print int(f(n+5)-f(n-5)+f(n)%10);"*input()
Edit: New way to calculate particular number, saves another 4 symbols and allows to avoid int():
def f(n):exec"a=b=1;"+"a,b=b,a+b;"*(n-1);return a
exec "n=input()+6;print f(n+5)-f(n-5)+f(n)%10;"*input()
p=5**.5
f=lambda n:((1+p)**n-(1-p)**n)/(2**n*p)
exec"n=input();print 55*f(n)+88*f(n+1)+f(n+6)%10;"*input()
106 chars as long you don't care about int() function and accept a float
Sorry I did not read your question properly before posting. I am glad you at least found some use in it.
I don't know Python, but in Mathematica, as generic as possible:
f[1] = 1;
f[2] = 1;
f[x_] := f[x] = f[x - 1] + f[x - 2]
t = 0;
n = 35;
For[i = 0, i <= 9, i++, t += f[n + i]]
t += f[n + 246] ~Mod~ 10
Or, in terse Mathematica, still without using Fibonacci function:
f[1|2]=1;a:f#x_:=a=f[x-1]+f[x-2];Sum[f[#+x],{x,0,9}]+f[#+246]~Mod~10&
This one prints the Fibonacci series up to n.
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
I need a code that calculates nth fibonacci number as well as giving me the time used to calculate it, in python.
def fib(n):
if n==0 or n==1: return 1
else: return fib(n-1)+fib(n-2)
The calculation of the number step must use a such method.
This is a classic dynamic programming/recursion with memoization problem. Notice that in your code, you recursively call fib(x-1) a lot. This is a huge waste of effort: once you calculate it once, you should store it for later use so that you don't have to calculate it again. In Python 3 you can do this with the glorious functools.lru_cache
#lru_cache(maxsize=None)
def fib(n):
if n < 1:
return n
else:
return fib(n - 1) + fib(n - 2)
Unfortunately, since nobody uses Python 3.2 yet, you'll have to write your own. Here's some pseudocode:
cache = {0: 0, 1: 1}
def fib(n):
if n in cache:
return the cached value
else:
calculate fib(n) recursively
store the value in the cache
return the value
This technique is known as recursion with memoization. Equivalently, you can use dynamic programming: calculate the values from the bottom up:
fibs = [0, 1]
for i in range(2, n):
calculate fibs[i] using the previous values in fibs
append the new value
To time these functions, put them in a module (a file ending in .py) and use timeit from the command line:
(change directory to the one containing your module)
python -mtimeit "import <name of module>" "fib(3000)"
By the way, there is a closed-form expression for the nth Fibonacci number, which may prove faster/more useful:
where
Use the timeit module to time the function:
import timeit
def fib(x):
if x==0 or x==1: return 1
else: return fib(x-1)+fib(x-2)
print timeit.Timer('fib(5)', 'from __main__ import fib').timeit()
Output:
3.12172317505
To directly answer the question in the title, you can use time.time() to get the current time since the epoch in seconds and keep calculating the subsequent fibonacci number until the time limit is reached. I've chosen to use an efficient method of computing fibonacci numbers below to give you a better demonstrating of this concept.
def fibTimeLimited(limit):
start = time.time()
n, f0, f1 = 1, 0, 1
while time.time() < start + limit:
n += 1
f0, f1 = f1, f0+f1
return (n, f1)
Sample output:
Calculated 1st fibonacci number as 1 in 0.000001 seconds
Calculated 31st fibonacci number as 1346269 in 0.000010 seconds
Calculated 294th fibonacci number as 12384578529797304192493293627316781267732493780359086838016392 in 0.000100 seconds
Here is a very simple example that uses Python tuples instead of recursion.
import time
def fib(n):
cnt = 1
if n == 0:
return a
a = 0
b = 1
while n > cnt:
(a, b) = (b, b+a)
cnt += 1
return b
start = time.time()
result = fib(15)
runTime = time.time() - start
print result, runTime