Python Fibonacci using [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Good day, I want to write a python code to recursively calculate the entries of the Fibonacci sequence using a function. This function should take in as input an integer number which should denote the limit after which the recursion should stop.
This is what I have:
def fib2(n: int) -> int:
if n<2:
return n
return fib2(n - 2) + fib2(n - 1) # recursive case
If I call this function, say fib(4) I only get '4' returned, whereas I expect a set of calls, namely the recursion calls. Where is the mistake?
Edit: Thanks for the tips. I'm just at the beginning of learning Python and realized after the fact that the code indeed worked out. So I'm getting the right output. The reason I was confused was that I was expecting to obtain the whole series of outputs leading to the final expression. Now I know that this would be possible using a for-loop, for example.

I think f(1) = 0 so you need to make it
def fib2(n: int) -> int:
if n==1:
return 0
elif n==2:
return 1
return fib2(n - 2) + fib2(n - 1) # recursive case
I think you have a mistake in actually implementing the Fibonacci algorithm.

Actually, the problem is in implementing the Fibonacci algorithm.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
According to Wikipedia Fibonacci number.
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
F(0) = 0, F(1) = 1
and
F(n) = F(n - 1) + F(n - 2) [where n > 1]
Sample Code
def fib(n: int) -> int:
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
Output
print(fib(4))
# 3

Related

Find index of Fibonacci Sequence with x digits (Project Euler Problem 25) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
This is my code, it works pretty well. I'm new to Python and programming in general. I wonder if this approach is okay... I saw this decorator in a video and I wonder if it's good practice to use it.
The problem: Project Euler Problem 25
from functools import cache
#cache
def fibonacci(n):
if n == 1 or n == 2:
F = 1
else:
F = fibonacci(n - 1) + fibonacci(n - 2)
return F
x = 1
while True:
x += 1
if len(str(fibonacci(x))) == 1000:
print(x)
break
That's one way to do it, and I think it's fine.
There are other ways to compute Fibonacci numbers quickly, e.g.,
applying a fast exponentiation algorithm to the recurrence.
For this problem, you can also get all the way to closed form. The
Fibonacci number F(n) satisfies
F(n) = ((1 + √5)/2)n + ((1 − √5)/2)n.
The second term goes to zero exponentially fast, so we can ignore it
unless there is a Fibonacci number very close to 10999 (there
isn't). The number F(n) has at least 1000 digits if and only if it's
greater than or equal to 10999, so we need to minimize F(n)
subject to
F(n) ≥ 10999,
which holds if and only if
log10 F(n) ≥ 999,
which is approximately equivalent to
log10 ((1 + √5)/2)n ≥ 999,
which holds if and only if
n log10 ((1 + √5)/2) ≥ 999,
so we should be able to take
n = ⌈999 / log10 ((1 + √5)/2)⌉.
your first line did´t run in my python interpreter,
if you like you can use the lru_cache:
Here an example from Geeks for Geeks:
from functools import lru_cache
import time
# Function that computes Fibonacci
# numbers without lru_cache
def fib_without_cache(n):
if n < 2:
return n
return fib_without_cache(n-1) + fib_without_cache(n-2)
# Execution start time
begin = time.time()
fib_without_cache(30)
# Execution end time
end = time.time()
print("Time taken to execute the\
function without lru_cache is", end-begin)
# Function that computes Fibonacci
# numbers with lru_cache
#lru_cache(maxsize = 128)
def fib_with_cache(n):
if n < 2:
return n
return fib_with_cache(n-1) + fib_with_cache(n-2)
begin = time.time()
fib_with_cache(30)
end = time.time()
print("Time taken to execute the \
function with lru_cache is", end-begin)

Returning the smallest integer of an increasing function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Write a function lowest_integer() which takes 2 input arguments:
a function f representing an increasing function 𝑓(𝑥),
a number fmin,
and returns an integer nmin such that 𝑛𝑚𝑖𝑛>0 is the smallest
integer that satisfies 𝑓(𝑛𝑚𝑖𝑛)>𝑓𝑚𝑖𝑛.
To test the function we use code like this where we define f(n) then
print(lowest_integer(f, fmin)) and get the expected output:
def f(n):
return 2*n
print(lowest_integer(f, 10))
## 6
def f(n):
return n**2 + 6*n - 3
print(lowest_integer(f, 500))
## 20
My attempt at the code:
def lowest_integer(f, fmin):
f = fmin
nmin = n + 1
return nmin
I'm having trouble figuring out how to define the function f(n) within the lowest_integer() function
You can loop through the integers starting at 1, until you find one that satisfies your condition, in that case, return it:
def lowest_integer(f, fmin):
nmin = 1
while True:
if f(nmin) > fmin:
return nmin
nmin += 1
def f(n):
return 2*n
print(lowest_integer(f, 10))
def f(n):
return n**2 + 6*n - 3
print(lowest_integer(f, 500))
Output:
6
20
This approach, of course, is a naive one, and will be slow if the function f is slow and fmin is very big, but in general it does good.
A faster approach would be using a library like sympy or something, that have functions that use more sophisticated methods and techniques that are suited to these kinds of problems.
def f(n):
return 2*n
def lowest_integer(f, fmin):
for findmin in range(fmin):
if f(findmin) > fmin:
return findmin
return -1
print(lowest_integer(f, 10))
You can do it like that :
def lowest_integer(f, fmin):
nmin=1
while f(nmin)<=fmin :
nmin += 1
return nmin
You begin with nmin = 1 and you add 1 to nmin while f(nmin)<=fmin. To do that, you can use a while loop.
By doing f(nmin), you call the function f and calculate its value for the entry nmin.

How can I repeatedly divide a number by the elements of a list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
divisors = []
def check_for_prime(x):
divisors = [x / d for d in list(range(x)) if x != any([0, 1, x])]
if isinstance(divisors, float):
yield x
When I try to run this code, it shows an error: 'list object cannot be interpreted as an integer'. How can I fix this so the loop can successfully divide everything?
It seems like you are trying to check if a given number is prime through list comprehension. There are a good bunch of things wrong with your logic-
divisors = [x / d for d in list(range(x)) if x != any([0, 1, x])]
I believe you're trying to find a list of divisors for x here. This makes no sense though, even if I assume that you thought x != any([0, 1, x]) means "if x is either 0, 1, or x" (that's not actually what this code means). Wouldn't that statement always be true? I mean x has got to be x (unless it's nan, but that's a different topic).
If you wanted to express "if x is either 0, 1 or x" in python, you'd use if x in [0, 1, x] (you shouldn't want to though since that makes 0 sense as explained above). Not any. Read what any does.
To get a list of divisors for x, you should instead do-
divisors = [d for d in range(2, math.floor(x/2) + 1) if x % d == 0]
Essentially, you start from 2 (not 0 because that's impossible, and not 1 because we want to avoid that for prime checking), and stop at half the given number (because after that point, you can't divide the given number and get an integral result). Throughout this range, you only add those d for which x % d is 0. I.E, the result is integral. Notice, 6 % 3 is 0, because 3 is indeed a divisor of 6.
I have 0 clue what the hell you're trying to do here though-
if isinstance(divisors, float):
yield x
You're checking whether or not divisors is a float? why? you already know it's a list, you made it in the previous line.
I think you want to know if the given number is a prime or not. In that case, you can just check if the length of divisors is more than 0.
return len(divisors) > 0
Edit: As #RiccardoBucco mentioned below. If you don't want the list of divisors at all, you can simply return as soon as you find a divisor. A simple loop will suffice for that.
for d in range(2, math.floor(x/2) + 1):
if x % d == 0:
# x is not prime
return False
# x is prime
return True
However, DO NOT forget to factor in the exceptional case when x = 1, 1 is not a prime number. Should be factored in both the for loop and the list comprehension method.
You are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in list.
This will always fail because you're creating a new list by using the comprehension in line 3. Line 4 will always evaluate to False because a list is obviously not a float.

What is going on in this code (Python 2.7)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
I received an assignment where I had to find the sum of all prime numbers up to 2 million and the code I wrote originally took way too long to run so the teacher gave me this algorithm to check if the number is prime. However, I don't quite seem to get what's going on in the return all statement and what it has to do with prime numbers
Since I was not nice to you. Let me just make a little extra effort and explain it you.
First read this:
http://wiki.planetmath.org/howtofindwhetheragivennumberisprimeornot
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
Let's see whats happening here.
Step1. if n % 2 == 0 and n > 2
Check if the number is divisible by 2 and also greater than 2. If these condition fail then the number is not prime. Don't proceed any further and return false.
Step2a. int(math.sqrt(n)) + 1
Calculate the square root of the number (it might be float so we convert it into int) and then add 1 to it.
Step2b. range(3, int(math.sqrt(n)) + 1, 2)
Create a list starting from 3 to the value calculated in step2a with a step size of 2. So basically it will get all the odd numbers from 3 to step2a value. Why just odd? Because evens are not prime!
Step2c. (n % i for i in range(3, int(math.sqrt(n)) + 1, 2)
In this step we are iterating over the list created in 2b and dividing n by all of those numbers (by dividing here i mean taking modulus) and we are storing the results in an iterator object.
Step2d. all()
If n was divisible by any number of list from 2b, then a 0 will be stored on n % i. And we know that a prime number is not divisible by any number other than 1 and itself. If we get a 0 then we are done, it's not a prime number.
all() will return true only if all the values are non zero.
Eg.
print all([1,2,3,4,5])-->True
print all([0,1,2,3,4])-->False
I hope, now it's clear to you.

recursive function in python adding? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So the question reads: Design a function that accepts an integer argument and return’s the sum of all integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function will return the sum of 1,2,3,4…….50. Use recursion to calculate the sum.
im having lots of trouble as you can tell by my code
def main():
numbers= int(input('Enter a number to add the sums: ')
mysum = sum_num(numbers,1)
def sum_num(numbers,mysum):
start=1
end=numbers
if start>end:
return 0
else:
return my_sum
main()
def sumup(n):
# this one is your emergency break. you return 1 if n gets below
# a certain threshold, otherwise you'll end up with an infinite
# loop
if n <= 1:
return n
# here is the recursion step, we return (n + "the sum to n+1")
else:
return n + sumup(n-1)
print(sumup(50))
Golfing a bit:
def sumup(n):
return (n + sumup(n - 1) if n > 1 else n) if isinstance(n, int) else None

Categories