Recursion not terminating in Python - python

I'm trying to write a program that finds if a given number is in the Fibonacci sequence and I keep getting recursion that doesn't terminate and I'm not sure why. Line 17 seems to be the big problem. When I input 0 or 1 I get the desired answers. Just looking for help getting to an answer, I'm trying to learn so just telling me the answer doesn't help me much.
number = int(input("Enter your number:"))
def fib(n):
if n == 0 or n == 1:
return 1
else:
return (fib(n-1) + fib(n-2))
def isfib(number):
n = 0
if number < 0:
print("Invalid input")
elif number == fib(n):
print("Number is in the sequence")
elif number < fib(n):
print("Number is not in the sequence")
elif number > fib(n):
n = n +1
isfib(number) #where the problem occurs
isfib(number)

There are many little mistakes so i corrected those(I have added a better implementation of Fibonacci code with simple addition too):
number = int(input("Enter your number:"))
def fib(n):
if n == 0 or n == 1: return 1
else:
temp1=1
temp=2
temp3=0
for z in range(n-2):
temp3=temp
temp+=temp1
temp1=temp3
return temp
def isfib(number): #it is ok not to return anything unless you need to stop the function in between
done=0
n=0
while done!=1:
if number < 0:
print("Invalid input")
done=1
elif number == fib(n):
print("Number is in the sequence")
done=1
elif number < fib(n):
print("Number is not in the sequence")
done=1
elif number > fib(n):
n = n +1
#i have used done instead of return to show the function can exit even if you dont return a value
#you can just 'return' instead of changing done variable and making the loop infinite
isfib(number)
Since you have used lot of recursions, i am guessing you want to do it only by using recursions. So, the code will be like this:
number = int(input("Enter your number:"))
def fib(n):
if n == 0 or n == 1: return 1
else: return (fib(n-1) + fib(n-2))
def isfib(number,n=0):
if number < 0: print("Invalid input")
elif number == fib(n): print("Number is in the sequence")
elif number < fib(n): print("Number is not in the sequence")
elif number > fib(n):
n = n +1
isfib(number,n)
isfib(number)
Tested of course, it works(but again i wouldn't recommend it this way :D)

Your fib function is wrong (one of the terms should be n-2)

The last elif of the isfib() function is not returning a call of itself,i.e it is calling itself and not doing anything with that result.

Put simply, you are calling isfib(number) with the very same number you were given originally. Your "n = n + 1" just before that suggests that maybe you wanted to call isfib(n) not isfib(number).
Basically isfib(number) is just an infinite loop.

I don't really know why you want to use recursive to solve this question. When you get a number, you don't know what are n-1 and n-2. Therefore, you cannot recursive on n-1 and n-2. The following example can easily check the number is in Fibonacci sequence or not:
number = int(input("Enter your number:"))
def fib(n):
ni = 1
ni_minus_1 = 0
while ni + ni_minus_1 < n:
temp = ni_minus_1
ni_minus_1 = ni
ni = ni + temp
if ni + ni_minus_1 == n:
return True
return False
print(fib(number))
update
I guess you want to build the sequence by recursive. For example, given number is 5, you want to return the 5th element in Fibonacci sequence. Then the code would be like the following:
def build_fib(n):
if n == 0:
return 0
if n == 1:
return 1
return build_fib(n-1) + build_fib(n-2)
print(build_fib(6))

Related

Write a python script to print all Prime numbers between two given numbers (both values inclusive)

Write a python script to print all Prime numbers between two given numbers (both values inclusive)
can anyone please tell what am I doing wrong here ?
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
for i in range(2,k):
if k%i!=0:
if k!=i:
continue
elif k==i:
print(k)
break
elif k!=i:
break
you are checking if a number is prime the wrong way there are many
unhandled cases in your code for example if a is larger than b
you will start looping from "a" anyway
and even if the values are sat up correctly the algorithm is not right
here is my optimal solution hope it will help
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
def is_prime(n):
# negative numbers cannot be primes 1 and 0 are also not primes
if n <= 1:
return False
# since 2 is the first prime we will start looping from it
# until n since you mentioned that n is included
for i in range(2, n + 1):
# if n is cleanly divisible by any number less than n
# that means that n is not prime
if n % i == 0 and n != i:
return False
return True
for k in range(a,b):
if a > b:
print ("a cannot be bigger than b")
if is_prime(k):
print(k)
Here's the solution. I added some comments to explain what the code does.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
# Include b in the range by adding 1
for num in range(a, b + 1):
# Prime numbers are greater than 1
if num > 1:
for i in range(2, num):
# If the number is divisible, it is not prime
if num % i == 0:
# Check if the number is equal to the number itself
if num != i:
break
else:
# If the loop was not broken, the number isn't divisible
# by other numbers except itself and 1, so it's prime
print(num)
Well, a prime is "a number that is divisible only by itself and 1", so to actually first I would go only to range(2, k-1). This approach you have is one of the most straightforward ways of doing it, and is not computationally friendly. There are algorithms that specialize in this kind of prime number finding.
I have fixed the code, simplifying the expressions and adding like already mentioned +1 for inclusivity.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b+1):
for i in range(2,k+1):
if k==i:
print(k)
elif k%i!=0:
continue
else: # is divisible and isn't 1 or the number
break
I encourage you to see this post, how they do it.
An other way of doing it would be:
#Check only 1 number at time:
def check_prime(check):
if check > 1:
for i in range(2, check):
if check % i == 0:
return False
return True
return False
#then check your numbers in a loop
list_prime = []
for i in range(50, 250):
if check_prime(i):
list_prime.append(i)
print(list_prime)
That way you can check 1 possible prime number at time.
If you need numbers in between just put it in loop.
Usually, when generating prime numbers utilizing some form of the "Sieve of Erotosthenes" algorithm, it is only necessary to check for denominator values up to the square root of the number being evaluated. With that in mind, here is one more possible take on your prime number loop test.
import math
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
if k == 2 or k == 3: # Pick up the prime numbers whose square root value is less than 2
print(k)
x = int(math.sqrt(k) + 1) # Need only check up to the square root of your test number
for i in range(2,x):
if k%i!=0:
if x-1 > i:
continue
else:
print(k)
else: # If the remainder is zero, this is not a prime number
break
Another version to try.

What is the flaw with my logic in a python function for checking primes?

I'm relatively new to Python and trying to build a function to check primes because I thought it would be a good starter project, but my code returns everything as a prime, so it's obviously gone wrong. I get this is an inefficient way to do it, but I want to understand how to do it the long way first. Here's my code so far:
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 0:
if n % i == 0:
break
print("This number is not prime.")
else:
i = i - 1
print("This number is prime.")
def Main():
n = int(input("What is the number you'd like to check?"))
Prime(n)
answer2 = input("Thank you for using the prime program.")
Main()
Mathematically speaking you could check only all the int between 0 and sqrt(n) to judge a number is prime or not as for the logic, you are missing negative number handling plus other things please see my following code:
def prime(n):
n = abs(n)
if n<4: return True
i = int(sqrt(n))
while i > 1:
if n % i == 0: return False
i -= 1
return True
plus you should add this to your import
from math import sqrt
Here is your program with a couple changes:
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 1:
if n % i == 0:
print("This number is not prime.")
return
i = i - 1
print("This number is prime.")
return
def Main():
n = int(input("What is the number you'd like to check? "))
Prime(n)
print "Thank you for using the prime program."
Main()
First, i is now compared until i > 1 rather than 0 as every number is divisible by 1 and hence all numbers would be prime if the original condition was used.
Secondly, the break statement is substituted with return. Although break would work, the program would need more modifications in that case because the message for a prime number would always be printed at the end (along with not a prime message). Also, the return statement was moved after the print to actually get a print. More importantly, the message that a number is a prime was moved outside the while - otherwise the message would be printed on every iteration.
I also removed the else and the i is decremented right in the while loop which is to me a more readable alternative.
Finally, your last statement was, I assume, supposed to be an output, which it is now. I also added a space to the user prompting message so that the number displays more nicely.
It's not easy to explain the logic flaw, but you can see the following code
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 0:
if i == 1 or n == 2 or n == 3:
print("This number is prime.")
break
if n % i == 0:
print("This number is not prime.")
break
else:
i = i - 1
def Main():
n = int(input("What is the number you'd like to check? "))
Prime(n)
print("Thank you for using the prime program.")
Main()
Ok, first off, your code will never print "This number is not prime." because you've put a break statement right before it. You would want to reverse those two lines such that it becomes:
print("This number is not prime.")
break
Also, the line i = n - 1 should be changed to i = n so that you check the starting number as well, and not just the numbers lesser than it. So if you try the code now, you'll notice that you're printing whether every number that you check is prime or not, not just the input value. To remedy this using your code structure, use a flag. For example:
def Prime(n):
flag = true
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n
while i > 0:
if n % i == 0:
print("This number is not prime.")
break
else:
i = i - 1
if flag == true:
print("This number is prime.")
The flag check should be outside the loop.

Collatz Sequence. (Python 3)

I've started the book "Automate The Boring Stuff" by Al Sweigart.
At the end of Chapter 3, the author suggests creating a Collatz Sequence in Python as a practice exercise. (the practice exercise suggests I use a the print function and return statement)
When I use a print() function in my code, it works great and I get all the evaluated values I want to see on the screen:
print("This is The Collatz Sequence")
user = int(input("Enter a number: "))
def collatz(n):
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
print(n)
else:
n = n * 3 + 1
print(n)
collatz(user)
Question:
How come when I want to use the return statement, the while loop only runs once?
For example, passing the integer 3 into my function with the return statement only gives me the return value of 3 and 10:
print("This is The Collatz Sequence")
user = int(input("Enter a number: "))
def collatz(n):
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
return n
else:
n = n * 3 + 1
return n
result = collatz(user)
print(result)
return exits the function and, therefore terminates your while loop.
Perhaps you meant to use yield instead:
print("This is The Collatz Sequence")
user = int(input("Enter a number: "))
def collatz(n):
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
yield(n)
else:
n = n * 3 + 1
yield(n)
print(list(collatz(user)))
Output:
This is The Collatz Sequence
Enter a number: 3
3
[10, 5, 16, 8, 4, 2, 1]
Yield is logically similar to a return but the function is not terminated until a defined return or the end of the function is reached. When the yield statement is executed, the generator function is suspended and the value of the yield expression is returned to the caller. Once the caller finishes (and assumably uses the value that was sent) execution returns to the generator function right after the yield statement.
In your code you don't re-feed the new value back into your equation. Try separating your while loop from the collatz module. I have an example of this below:
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
chosenInt = int(input('Enter an integer greater than 1: '))
print(chosenInt)
while chosenInt != 1:
chosenInt = collatz(chosenInt)
print(chosenInt)
def collatz(number):
if (number%2 == 0):
return print(number//2);
else:
return (print(number*3+1));
inputNumber = input("Enter a number greater than 1:");
result = collatz(int(inputNumber));
while result != 1:
result = collatz(result);
I am getting a typeError with it! Don't know why?

Printing only nth number of prime sequence, python

I'm trying to write a program in python that can either print 1 through nth numbers of the prime number sequence, or print just the nth number of the prime number sequence. Here is the code.
import math
P = 2
X = raw_input('Choose a number: ')
Y = 1
def prime(P, Y):
Choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
if Choice == "1":
while Y <= int(X):
isprime = True
for x in range(2, int(P) - 1):
if P % x == 0:
isprime = False
break
if isprime:
print P
Y += 1
P += 1
elif Choice == "2":
prime(P, Y)
Basically, i have the first part down, so that it prints 1 through nth numbers of the prime sequence. However, I'm quite lost on how to make it calculate just the nth prime, where the nth prime is the given through raw input. It must be possible to do this in python, however, how would it be done, and what would be the best way to do so, without having to add too many new variables that i don't have here, (though i would be fine doing so). Help would be appreciated.
Add a condition so that if either the user wants to print all numbers, or you have reached the final prime number of the sequence, the number will be printed. (I have also replaced some of the variable names with more descriptive ones, and altered it so that the function is passed the number_of_primes as its only parameter, which would seem to make more sense.)
def print_primes(X):
choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
count = 1
n = 2
while count <= X:
is_prime = True
for i in range(2, int(n) - 1):
if n % i == 0:
is_prime = False
break
if is_prime:
if choice == "1" or count == X:
print n
count += 1
n += 1
number_of_primes = int(raw_input('Choose a number: '))
print_primes(number_of_primes)
Just only print if it's the Yth number:
if isprime:
Y += 1
if Y == X:
print P

How do I print a fibonacci sequence to the nth number in Python?

I have a homework assignment that I'm stumped on. I'm trying to write a program that outputs the fibonacci sequence up the nth number. Here's what I have so far:
def fib():
n = int(input("Please Enter a number: "))
if n == 1:
return(1)
elif n == 0:
return(0)
else:
return (n-1) + (n-2)
mylist = range[0:n]
print(mylist)
I'm thinking I could use separate functions but I can't figure out how to pass the argument that calculates the fibonacci sequence. Then the next step would be to to print out the sequence of numbers up to that number.
Non-recursive solution
def fib(n):
cur = 1
old = 1
i = 1
while (i < n):
cur, old, i = cur+old, cur, i+1
return cur
for i in range(10):
print(fib(i))
Generator solution:
def fib(n):
old = 0
cur = 1
i = 1
yield cur
while (i < n):
cur, old, i = cur+old, cur, i+1
yield cur
for f in fib(10):
print(f)
Note that generator solution outperforms the non-recursive (and non-recursive outperforms recursive, if memoization is not applied to recursive solution)
One more time, recursive with memoization:
def memoize(func):
memo = dict()
def decorated(n):
if n not in memo:
memo[n] = func(n)
return memo[n]
return decorated
#memoize
def fib(n):
#added for demonstration purposes only - not really needed
global call_count
call_count = call_count + 1
#end demonstration purposes
if n<=1:
return 1
else:
return fib(n-1) + fib(n-2)
call_count = 0 #added for demonstration purposes only - not really needed
for i in range(100):
print(fib(i))
print(call_count) #prints 100
This time each fibbonacci number calculated exactly once, and than stored. So, this solution would outperform all the rest. However, the decorator implementation is just quick and dirty, don't let it into production. (see this amazing question on SO for details about python decorators :)
So, having fib defined, the program would be something like (sorry, just looping is boring, here's some more cool python stuff: list comprehensions)
fib_n = int(input("Fib number?"))
fibs = [fib(i) for i in range(fib_n)]
print " ".join(fibs)
this prints all numbers in ONE line, separated by spaces. If you want each on it's own line - replace " " with "\n"
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(int(input())))
And since you want to print up to the nth number:
[print(fibonacci(n)) for n in range (int(input()))]
And for python2.7 change input to raw_input.
Please note, in your call
You are not calling fib() recursively
You need a wrapper method so that the input is not requested every time the method is called recursively
You do not need to send in a list. Just the number n is good enough.
This method would only give you the nth number in the sequence. It does not print the sequence.
You need to return fib(n-1) + fib(n-2)
def f():
n = int(input("Please Enter a number: "))
print fib(n)
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1)+fib(n-2)
This might be faster incase of long list
# Get nth Fibonacci number
def nfib(nth):
sq5 = 5**.5
phi1 = (1+sq5)/2
phi2 = -1 * (phi1 -1)
resp = (phi1**(nth+1) - phi2**(nth+1))/sq5
return long(resp)
for i in range(10):
print i+1, ": ", nfib(i)
OUTPUT
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5
6 : 8
7 : 13
8 : 21
9 : 34
10 : 55
def fib(n):
if n == 1:
return(1)
elif n == 0:
return(0)
else:
return fib(n-1) + fib(n-2)
my_num = int(input("Enter a number:"))
print fib(my_num)
Im not really sure what your question is... but the answer is probably something like this
Separate functions would be best, as the recursive function would be far easier to deal with. On the other hand, you could code an iterative function that would take only one parameter
Recursively::
def fib(n):
if n == 1:
return (1);
elif n == 0:
return (0);
else:
return fib(n-1) + fib(n-2);
def callFib():
n = int(raw_input('Enter n::\t'));
mylist = fib(n);
print mylist;
callFib();
Iteratively::
def fib():
n = int(raw_input('Enter n::\t'));
terms = [0,1];
i=2;
while i<=n:
terms.append(terms[i-1] + terms[i-2]);
i=i+1;
print terms[n];
fib();
for a recursive solution:
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
x=input('which fibonnaci number do you want?')
print fib(x)
explanation:
if n is 0, then ofcourse the '0th' term is 0, and the 1st term is one. From here, you know that the next numbers will be the sum of the previous 2. That is what's inferred by the line after the else.
It looks like you might be trying to solve the same homework problem I was, where you don't actually need user input. You just pass in the parameter when you call the function.
def compute_nth_fib(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
return compute_nth_fib(num-1) + compute_nth_fib(num-2)
#test with different parameters
print(compute_nth_fib(3))
Hope that's helpful to someone!

Categories