Fibonacci sequence in python given number n [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have tried to creat a code,that given number n,it will print F[n] (wereas F the function i created in order to calculate the fibonacci number) .But apparently there is something wrong because no matter the input,the result is always 1.Heres is the code:
def fib(n):
a=1
b=1
x=1
for i in range(n):
a=b
b=x+b
x=a
return a
n=input()
print fib(n)

Python is a whitespace sensitive language. The scope of a block of code in Python is determined by the level of indentation so:
def fib(n):
a=1
b=1
x=1
for i in range(n):
a=b
b=x+b
x=a
return a # <--- the first time you run through the loop you return
return a is in the for loop as it is indented at the same level as the rest of the for loop. So the first time you run through the loop you reach the return statement which leaves the function at that point in time. This is most likely not what you want. You need to take the return outside the for loop, like so:
def fib(n):
a=1
b=1
x=1
for i in range(n):
a=b
b=x+b
x=a
return a # <--- now no longer in the loop.
Now the loop will run through all of range(n) and you can return your result after that.

Related

Python won't accept large numbers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to find the largest prime factor of a number. Below is my code in Python. When I input 600851475143, it doesn't give me an output. Is this code wrong?
def prime(n):
list = []
only_primes = []
for i in range(2,int(n)):
if n%i==0:
list.append(i)
for number in list:
if isprime(number)==True:
only_primes.append(number)
print(max(only_primes))
def isprime(k):
for z in range(2,int(k**1/2)+1):
if k%z==0:
return False
return True
print(prime(600851475143))
There are a couple things wrong here.
Most notably, the indentation on your 2nd for loop is off which is causing that loop to be ran every single iteration of the first for loop. It should be at the same indentation as the first so it can run strictly after.
Your algorithm is still far too slow to compute the largest prime factor of the number 600,851,475,143. It will only run in a feasible amount of time for numbers in the millions range. If you would like to run computations for numbers of that size, you will have to use a more advanced technique.
You are missing parentheses for the exponent in isprime's for loop.
In the case that your input number happens to be prime, your code will crash due to the only_primes list being empty.
Here is a fixed version:
def prime(n):
list = []
only_primes = []
for i in range(2, int(n)):
if n % i == 0:
list.append(i)
for number in list:
if isprime(number):
only_primes.append(number)
if len(only_primes) > 0:
return max(only_primes)
return n
def isprime(k):
for z in range(2, int(k**(1/2) + 1)):
if k % z == 0:
return False
return True
print(prime(1001))

How would I use a function with two variables python? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm supposed to calculate an approximation for the absolute value of any integer x. I need to write a function abs_approx(x, N) that calculates the N first terms of the sum and returns f(x). I am to use the function to compute the approximation for N=1,2,3,4.
The function is:
This is my following program, but I get that the absolute value of 1 is 0.3009465364104349. Which is completely wrong. Anyone see what I'm doing wrong?
from math import pi, cos
def abs_approx(x,N):
N=4
sum=0
for n in range(0,N+1):
num=cos((2*n-1)*x)
denom=(2*n-1)**2
sum+=num/denom
f=pi/2-4/pi*(sum)
return f
print(abs_approx(1,1))
print: 0.3009465364104349
Did you mean to loop from 1 to N?
from math import pi, cos
def abs_approx(x, N):
sigma = 0
for n in range(1, N + 1):
num = cos((2*n-1)*x)
denom = (2*n-1)**2
sigma += num/denom
f = (pi/2) - (4/pi*(sigma))
return f
print(abs_approx(1, 4))
Output:
0.988880798353344

Python script- need help understanding this while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My gf is studying CS and needs help understanding how this script runs and why?
What value does mystery(9870) return?
def mystery(n):
m = " "
while n > 0:
m += str(n % 10)
n //= 10
return m
The possible answers are-
"789"
"0789"
"7890"
"987"
"9870"
We just need to know how the code runs?
Can anyone help?
This is the proper indentation you need to use.
def mystery(n):
m = ""
while n > 0:
m += str(n % 10)
n //= 10
return m
When you call the function:
mystery(9870)
' 0789'
The function takes a parameter and checks if it is greater than 0. While the condition is satisfied, it divides the number by 10 and converts the remainder into a string and appends it to an empty string m. n //= 10 will remove the last digit of the number and stores the remaining in n. And the while loop checks if n is greater than 0 again. Etc.. The whole thing continues until n is a single digit number at which point, n//=10 will return 0 and the condition of while loop will not satisfy.
Basically, it reverses the digits of the number you pass as parameter.
Hope this explanation helps.

Using a while loop to calculate the factorial of numbers between 0 and 10 in Python? [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 5 years ago.
Improve this question
I have a simple program to calculate the factorial of a user inputted value, however, I want to write a program to output the values of the factorials of each number from 0 to 10. (inclusive)
my program:
def factorial(n):
f = 1
while (n > 0):
f = f * n
n = n - 1
return f
Thank you!
This question is probably destined for oblivion, but it costs nothing to answer.
#your function
def factorial(n):
f = 1
while (n > 0):
f = f * n
n = n - 1
return f
#a new function that loop the first one
def factorial_loop(n):
#in Python 2.x, you should use xrange() instead of range()
for i in range(n+1):
print(factorial(i))
factorial_loop(10)
You need to iterate your factorial recursive function from 1 to 10 and put the index as your argument.
I urge you to try to do this and code it, in order for you to improve your coding skills.
Hope it helps.

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