why my Python recursive function not working? - python

Hey everyone hope you all doing great!
I was practicing my python, I write a code to execute the factorials of the given Number but the code didn't execute!
The code
def factorial_recursive(n):
if n == 1 or n == 0:
return 1
return n * factorial_recursive(n-1)
f = factorial_recursive(5)
print(f)
After running Python File: None
where the answer must be 120 as factorial of 5 is 120

You have your second return statement indented in the if statement. The second return should be for any other cases. Here is the correct function:
def factorial_recursive(n):
if n == 1 or n == 0:
return 1
return n * factorial_recursive(n-1)
f = factorial_recursive(5)
print(f)
Outputs: 120

You need to call the function like so:
f=factorial_recursive(4)
print(f)
If you actually want to use it on some number (like 4).
Also, you should learn to format your code on stack overflow. Makes it easy for others to understand your code.

Related

Trouble understanding bug leetcode problem 202 Happy Numbers Python

Hey all just started practicing leetcode problems in python and was confused as to why my code wasn't working. I seem to be having a problem with undefined name when I try to run my code. Appreciate the help. Getting runtime error saying that n = solvingThisThing(n) is not defined
class Solution:
def solvingThisThing(n: int):
sum_of_squares = 0
digit = 0
while(n!=0):
digit = n % 10
sum_of_squares += (digit * digit)
n = n // 10
return sum_of_squares
def isHappy(n: int):
past_nums = set()
past_nums.add(n)
while(True):
if(n == 1):
return True
n = solvingThisThing(n)
if n in past_nums:
return False
else:
past_nums.add(n)
return False
Since the solvingThisThing method is a part of the Solution class, you have to run it from the solution class.
n=Solution.solveThisThing(n)
should work instead of
n=solveThisThing(n)

What is wrong with my python hyperoperation recursive function?

I tried to use the definition from Wikipedia for Hyperoperations and translate it into Python code.
My goal was to make it readable, making it fast was a task for later.
Here's the definition I used and below it is my code.
from Wikipedia: https://en.wikipedia.org/wiki/Hyperoperation#Definition
And now here's my code:
def hyperation(n, a, b):
if n == 0:
return b+1
if n == 1 and b == 0:
return a
if n == 2 and b == 0:
return 0
if n >= 3 and b == 0:
return 1
return hyperation(n-1, a, hyperation(n, a, b-1))
When I tried it with hyperation(n=1, a=3, b=3), what should basically be the same as
3 + 3
I always hit the recursion limit, doesn't matter how high I set it.
When trying this on paper by hand, it works perfectly fine. And while debugging I couldn't figure out what happens.
Thanks for every help!!!
In your last line the return keyword is missing.
First, your code was not formatted right, cause python is a indentation sensitive language.
Second, The last line of the error log indicates that the error is the addition of NoneType and int. You didn't return anything in the final else block, so that will return NoneType. Just add return at the beginning of the last sentence.
Third, you can delete every elif after return and just use if.

Python fibonacci unexpecred indent

Im new to code and learning python . I got homework to make print Fibonacci
numbers for N = 11 and N = 200 using method called Memoization . I found solution but when im running the code i getting two things : 1 .
Traceback (most recent call last):
**File "python", line 7
if n== 1:
^**
**IndentationError: unexpected indent**
and second i got empty result sometime when im running. what is wrong which the code :
def fibonacci (n) :
# If we have cached the value, then return it
if n in fibonacci_cache:
return fibonacci_cache[n]
# Compute the Nth term
if n== 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = fibonacci(n-1) + fibonacci(n-2)
# Cache the value and return it
fibonacci_cache[n] = value
return value
print(n, ":", fibonacchi(11))
See #Alexis Drakopoulos for a direct fix to your code. If you want to simplify implementing memoization you can use a decorator called lru_cache.
from functools import lru_cache
#lru_cache(maxsize=None)
def fibonacci(n):
if n<= 2:
return 1
return fibonacci(n-1)+fibonacci(n-2)
def fibonacci(n):
# If we have cached the value, then return it
if n in fibonacci_cache:
return fibonacci_cache[n]
# Compute the Nth term
if n == 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = fibonacci(n-1) + fibonacci(n-2)
# Cache the value and return it
fibonacci_cache[n] = value
return value
print(n, ":", fibonacchi(11))
in Python indentation is everything, I am not sure if this is correct with the last lines with the cache.
I suggest using 4 spaces (using tabs) in order to be consistent.
Python looks at indentations to understand what you are trying to do.
Welcome to programming in Python and to StackOverflow :-)
There are three problems with your code:
1. The indentation: Python needs you to pay attention to the indentation, such that code at a particular level is indented the same amount.
For code that runs after something like an if statement, you need to put the next block of code indented. Then when you have the elif (which is at the same level as the if statement) you need to bring the indenting back out to match the level of the if.
You can indent with spaces or tabs, but you need to be consistent (ie stick to one)
It's possible that the editor you're using has messed up the intenting when you pasted the code in, and it's also possible that some of the indenting got messed up when you put it into StackOverflow too, but you need it to look like that below. In this case, each intent is two spaces (so indenting is first no spaces, then two spaces, then four spaces etc.)
2. Typos: The final statement has a typo (so you're not actually calling the function you define!)
3. Fibbonacci_cache: it isn't defined, so that's been added at the top
Hope that helps - good luck with the rest of your journey into programming... it will need perseverance but you'll get the hang in time I'm sure!
fibonacci_cache = {}
def fibonacci (n) :
# If we have cached the value, then return it
if n in fibonacci_cache:
return fibonacci_cache[n]
# Compute the Nth term
if n== 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = fibonacci(n-1) + fibonacci(n-2)
# Cache the value and return it
fibonacci_cache[n] = value
return value
print("n:", fibonacci(11))

Recursion program flow

I have some textbook code that calls itself recursively. I don't understand the program flow. Here is the code:
def Recur_Factorial_Data(DataArray):
numbers = list(DataArray)
num_counter = 0
list_of_results = []
for num_float in numbers:
n = int(num_float)
1. result = Recur_Factorial(n)
list_of_results.append(result)
def Recur_Factorial(num):
if num == 1:
2. return num
else:
result = num*Recur_Factorial(num-1)
3. return result
if num < 0:
return -1
elif num == 0:
return 0
else:
return 0
In Recur_Factorial_Data, I loop through the data elements and call Recur_Factorial, which returns its value back to the calling function (Recur_Factorial_Data). I would expect that the lines marked 2 ("return num") and 3 ("return result") would always return a value back to the calling function, but that's not the case. For example, where the initial value (from the array DataArray) is 11, the function repeatedly calls itself until num is 1; at that point, the program falls to the line marked 2, but it does not loop back to the line marked 1. Instead, it falls through to the next line. The same happened on the line marked 3 -- I would expect it to return the result back to the calling function, but it does that in some cases and not in others.
I hope this is enough description to understand my question -- I just don't know why each return does not loop back to return the result to the calling function.
EDIT: The question at Understanding how recursive functions work is very helpful, and I recommend it to anyone interested in recursion. My question here is a bit different -- I asked it in the context of the program flow of the Python code where the recursive function is called.
If it call itself recursively 10 times, it will be at the 10th level of recursion and should go back 10 times at the point where there was a recursive call with an intermediate result and only then exit from the recursive function to the place where it was called. Learn more about recursion
Also try to rearrange instructions in Recur_Factorial function in this way:
def Recur_Factorial(num):
if num < 0:
return -1
elif num == 0:
return 0
elif num == 1:
return num
else:
return num * Recur_Factorial(num-1)

Confused with recursive functions in python

Hey guys am new to python app development.i have came to learn about recrusive functions in python. The code which i have done
def something(a):
if a == 0:
return 0
else:
return 2 + something(a)
When i called the function like pythons(5) it calls me error like TypeError: something() missing 1 required positional argument: 'b'
I would like to do add two to a number like if i call something(5) it must return 5+2 = 7
I dunno why am getting this error.Hope you guys can help me out in solving this..I aplogise if this is a low grade question on so..
Any help would be appreciated ..Thanks in advance..
There are a couple of issues here. Firstly python code is whitespace sensitive when it comes to indentation (note that the question got edited, the formatting was not correct previously). Then secondly you need to match up the number of arguments provided to the functions:
def pythons(a,b):
if a == 0:
return a
else:
return a * pythons(a,b-1)
When you write def pythons(a,b): you are defining a function with the name pythons and you are specifying that it takes exactly 2 arguments, a and b. Previously you tried to call it with pythons(b-1), the error message tells you exactly what has gone wrong, you only provided 1 argument when the function expected to get 2 arguments.
That is because in your method, when you recursively call pythons, you are not passing two arguments. This is probably what you want:
def pythons(a,b):
if a == 0:
return a
else:
return a * (b-1)
or simply (with same results):
def pythons(a,b):
return a * (b-1)
If your aim is to add two numbers recursively then this would be a more appropriate recursive function.
def add(a, b):
if a == 0 and b ==0:
return 0
elif b == 0 and a>= 0:
return 1 +add(a-1, 0)
elif a ==0 and b>= 0:
return 1 + add(0, b-1)
else: return 2 + add(a-1, b-1)

Categories