Python program, no output displayed when i run - python

python newbie here. I have a code below, but when i run the code nothing displays.
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci (n-1) + fibonacci (n-2)
what am I missing ? is it a print statement ? when i add print (), I get 327 as the result, but i don't think that is Fibonacci series.

This will print out the first 10 fibonacci numbers according to your code. Without a print statement, you will see no output.
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci (n-1) + fibonacci (n-2)
for i in range(10):
print(fibonacci(i))
Your current fibonacci() function just returns the value, you can either take that return value and print it, as I did above, or not return anything and just print the value directly in the function (see below)
def fibonacci(n):
if n <= 1:
print(n)
else:
print(fibonacci (n-1) + fibonacci (n-2))
for i in range(10):
fibonacci(i)

Related

Recursive function to check if a given number is Fibonacci

I'm new to python and I'm am having problems building a recursive function that checks if a given number is a Fibonacci number.
This is my code.
def isFib(n):
if n <= 1:
return n
else:
return (n - 1) + (n - 2)
if isFib(n) == 1 or isFib(n) == isFib(n - 1) + isFib(n - 2):
return True
It should print True in both cases, but instead it print True and False, and I can't find what's wrong
print(all([isFib(i) for i in [1,2,3,5,8,13,21,34,55]]))
print(all([not isFib(2*i) for i in [1,2,3,5,8,13,21,34,55]]))
The first part of your function is an if statement. If True, it returns a value - if False, it also returns a value. So, the second part of your function cannot possible execute, and the function isn't recursive (since you don't call the function again in either return statement).
More generally, what you're doing will never work. The logic seems to be: "a Fibonacci number is the sum of the previous Fibonacci number and the number before that, so I can reverse that logic by computing n - 1 and n - 2 and if they are Fibonacci numbers, then so is n" - or something like that.
But that doesn't work: 5 is a Fibonacci number, but (5-1) is not, so the logic breaks right there. If you were thinking only the sum needed to be a Fibonacci number: 13 is a Fibonacci number, but (13-1) + (13-2) = 23 and that's not a Fibonacci number either.
An easy way to solve this would be to just generate a Fibonacci sequence and return True as soon as the number you're checking comes up:
def is_fib(n, seq=None):
if seq is None:
seq = [0, 1]
# n is Fibonacci if the last number in the sequence is
# or if the last number has not yet past n, then compute the next and try again
return n == seq[-1] or (seq[-1] < n and is_fib(n, seq + [seq[-2] + seq[-1]]))
print([is_fib(i) for i in [1,2,3,5,8,13,21,34,55]])
print(is_fib(23))

Why am I getting nonetype when calling a function within a function in Python?

I'm tying to do a Collatz sequence with python code. I'm supposed to make a function that, given n, calculates the next number in the sequence. I want the next function "write" to print each number within the sequence.
My code so far:
def collatz(n):
while n != 1:
if n % 2 == 0:
n = n/2
return write(n)
else:
n = 3*n+1
return write(n)
def write(n):
print(n)
print(collatz(n))
write(6)
It gives me the right sequence, which should be 6, 3,10,5,16,8,4,2,1, but also gives me 9 "nones".
I'm new to programming, it should probably be something easy, but I can't figure out what.
write() is a function that executes two print() statements, and then implicitly returns None (since there are no return statements in the function).
You can simplify the code by using print() directly in collatz(), and eliminating the mutual recursion:
def collatz(n):
while n != 1:
if n % 2 == 0:
n = n//2
print(n)
else:
n = 3*n+1
print(n)
collatz(6)
#Here this will help you understand.
#When n becomes 1, the while loop is not executed,
#collatz does not return write(n)... thus returns None
def collatz(n):
while n != 1:
if n % 2 == 0:
n = n/2
return write(n)
else:
n = 3*n+1
return write(n)
#return None.... there is no return type, so this is implied
def write(n):
print(n)
result = collatz(n)
if result != None:
print(collatz(n))

get RecursionError when running Fibonacci function

def fib(n):
if n == 1 or n == 2:
return 1
return fib(n-1) + fib(n-2)
for i in range(5):
print(fib(i))
I want to print first 5 result of Fibonacci sequence only to get
RecursionError: maximum recursion depth exceeded in comparison
I think there is an exit of every positive n and print(fib(4)), print(fib(20)) and print(fib(100)) works perfectly.
What's wrong with my code?
range(5) starts at 0 and since you are not checking for 0 in your function, the recursion never ends.
As a sidenote, you are not calculating the fibonacci sequence correctly, you should add up
fib(n-1) + fib(n-2)
Try this:
def fib(n):
if n <= 2:
return n
return fib(n-1) + fib(n-2)
A generally better approach at calculating the n-th fibonacci number is to use a loop, since you end up calculating the same values over and over again if you use recursion. Using a loop you can do it like this:
def fibonacci(n):
if n < 2:
return 1
a = 1
fib = 1
for i in range(n-2):
a, fib = fib, a + fib
return fib
there is an exit of every positive n.
Yes, there is. But how about fib(0)?
Try print(list(range(5)))

a recursive function to calculate sum of a number digits

i have to write a recursive function which calculates sum of a number digits,here's the code i tried :
def sum_digit(n):
sum=0
a = n % 10
n //= 10
sum += a
while n > 0 :
sum = sum + sum_digit(n)
return sum
print(sum_digit(67154))
i don't know why i don't get the 23 as answer...my program doesn't come to an end
for example 23 number(please correct me if I'm wrong,I'm a newbie in python),the 3 goes to sum, and n become2,since its > 0 then it should go to while,so now it should calculate sum digit(2),the a become 2 and 2 goes to sum and n become 0 and sum digit(2) returns 2,then it sum with the 3 and i must get 5.
i appreciate your help.
You have an infinite loop because n never changes within the loop. Note that assigning a new value to n in the scope of the called function will not change n in the outer scope.
Also, it seems you are mixing an iterative solution with a recursive one. If you do the recursive call, you do not need the loop, and vice versa.
You can either do it recursively:
def sum_digit(n):
if n > 0:
return sum_digit(n // 10) + n % 10
else:
return 0
Or in an iterative way:
def sum_digit(n):
s = 0
while n > 0:
s += n % 10
n //= 10
return s
Or just using bultin functions (probably not what your teacher wants to see):
def sum_digit(n):
return sum(map(int, str(n)))
i must change the while with a if, and it works,thanks for your comments and sorry for posting such a question here.
This will do the trick:
def sum_digit(n, current_sum=0):
if n == 0:
return current_sum
else:
digit = n % 10
current_sum += digit
n //= 10
return sum_digit(n, current_sum)
The output:
print(sum_digit(67154))
> 23
You were mixing up an iterative method (the while loop) and the recursive method (the function call).
In a recursive function, must make sure you get these things right:
The end condition (in our case, we return the sum when the digit is 0)
and
The recursive call (in our case, going down one digit each time)
Change your code as following:
def sum_digit(n):
sum=0
a = n % 10
n //= 10
sum += a
if n > 0 :
sum = sum + sum_digit(n)
return sum
The reason is n is assigned new reference inside function, but it's invisible outside. so while part is loop died. In fact, while part is executed at most once, so code was changed as above.

Factorial in Python using while

why this function doesn't work as a factorial function?
def Factor(n):
while n>=1:
print n*(n-1)
return 1
This will work
def Factor(n):
val=1
while n>=1:
val = val * n
n = n-1
return val
You have recursion and iteration mixed. Take a look at these two:
def factor_recursion(n):
while n>=1:
return n * factor_recursion(n-1)
return 1
def factor_iteration_for(n):
factor = 1
for i in range(n):
factor *= i+1
return factor
def factor_iteration_while(n):
factor = 1
while n >= 1:
factor *= n
n -= 1
return factor
print factor_iteration_for(4)
print factor_iteration_while(4)
print factor_recursion(4)
You never change the value of n to anything other than what is passed into the function.
I don't think this is going to do what you think it will. Looks like you've mixed recursion and iteration.
First of all, none of your code changes the value of n, so the loop will run indefinitely unless n == 1 when the function is called.
Secondly, you aren't accumulating a partial product inside the loop (hint: before the loop set result =, then inside it multiply the current value of result by the value of n.
Finally, you should then return the accumulated result rather than one.
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
print factorial(5)

Categories

Resources