Recursion program flow - python

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)

Related

Variable location in recursion

The problem is my code keeps reflecting a variable as zero and this is caused by the fact that the variable is assigned at the start of my function, so each time I call the function the value evaluates to zero. However I need this variable assignment for the code to work and placing it within the elif statements still evaluates to zero and placing the the variable outside the function causes the function not work.
The aim of the program is to count pairs of consecutive letters in a string using recursion with no for/while loops in the code.
def countpairs(s):
pairs=0
if len(s)<2:
return 0 #base case
elif s[0].lower() == s[1].lower(): #recursion
pairs=+1
return countpairs(s[1:])
else: #recursion
pairs=+0
return countpairs(s[1:])
print(countpairs('Hello Salaam'))
This code is supposed to evaluate to 2 because of "ll" and "aa".
You need to wrap your head a little around what the recursion will do: it will call the function recursively to count the pairs from that point on, then (it should) add the pair, if any, found by this instance.
So your function needs to do something with the result of the recursive call, not just return it unchanged. For example, instead of this
elif s[0].lower() == s[1].lower():
pairs = +1
return countpairs(s[1:])
you might write this:
elif s[0].lower() == s[1].lower():
return countpairs(s[1:]) + 1
Something along these lines. You'll need to do a bit more work to get it just right, but I hope you get the idea.
The problems is that the variable pairs resets every recursive call...
When using counting recursive algorithms you don't need a variable that counts, that's the beauty
Instead, try to think how to recursive call can help you count.
def countpairs(s):
if len(s)<2:
return 0
elif s[0].lower() == s[1].lower():
return countpairs(s[1:])+1
else:
return countpairs(s[1:])
print(countpairs('Hello Salaam'))
There you go, in the recursive call the "counter" gets bigger every time it should be, think of the counter as a part of the function stack (or something like that).
You need to fix the syntax: pairs=+1 should be pairs+=1, same for pairs=+0. And you can pass the total into the next level.
def countpairs(s, pairs=0):
if len(s)<2:
return pairs #base case
elif s[0].lower() == s[1].lower(): #recursion
pairs+=1
return countpairs(s[1:], pairs)
else: #recursion
pairs+=0
return countpairs(s[1:], pairs)
print(countpairs('Hello Salaam')) # 2
You can do it by creating a recursive nested function and defining pairs in the outer function. Here's what I mean (with fixes for other issues encountered):
def countpairs(s):
pairs = 0
def _countpairs(s):
nonlocal pairs # Since it's not local nor global.
if len(s) < 2: # base case
return pairs
elif s[0].lower() == s[1].lower():
pairs += 1
return _countpairs(s[1:]) # recursion
else:
return _countpairs(s[1:]) # recursion
return _countpairs(s)
print(countpairs('Hello Salaam')) # -> 2
The code will always evaluate to zero because the last recursion will always have the length of s being less than 2. Instead use the global keyword to be able to grab the value of pairs.
numberOfPairs = 0
pairsList = []
def countpairs(s):
global numberOfPairs
if len(s)<2:
print("doing nothing")
return 0 #base case
elif s[0].lower() == s[1].lower(): #recursion
numberOfPairs+=1
newString = f"{s[0]} is equal to {s[1]}"
print(newString)
pairsList.append(newString)
return countpairs(s[1:])
else:
print(f"nothing happened: {s[0]}") #recursion
return countpairs(s[1:])
print(f"\nThe returned value of countpairs is: {countpairs('Hello Salaam')}")
print(f"Number of pairs: {numberOfPairs}")
print(pairsList)

How to return void in python

This is the famous coin change dp problem - given some coins return possible amount 11=2+2+2+5
arr=[2,5]
def Recur(amount,seq):
if amount==0:
print(seq)
return
if amount<0:
return
for coin in arr:
seq+=str(coin)
Recur(amount-coin,seq)
Recur(11,"")
Whatever I try to return the function returns one 2 more, that is it continues after the amount has reached 0. I tried to return 0,None, just return -- nothing works? It always continues after <0
arr=[2,5]
def Recur(amount,seq):
if amount==0:
print(seq)
return
if amount<0:
return
for coin in arr:
seq+=str(coin) # error is in this line since you are
#trying to update seq which persist across the method stack due
#to for loop calls Recur method again with this updated seq
#leading to extra addition of extra coin in seq.
Recur(amount-coin,seq)
Recur(11,"")
You need to update seq across the call so that hence do following modification:
arr=[2,5]
def Recur(amount,seq):
if amount==0:
print(seq)
return
if amount<0:
return
for coin in arr:
Recur(amount-coin,seq+str(coin))
Recur(11,"")

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))

recursive function python 3 'maximum recursion depth exceeded'

I am creating a collatz sequence with a recursive function below:
def collatz(n):
if n%2 == 0:
return int(n/2)
else:
return int((3 * n)/2)
From what I understand, a recursive function is a function that basically calls itself. Below I have attempted creating the recursive function with the following:
def collatz(x):
if x == 1:
"Done"
print(x)
x = collatz(x)
return(x)
Where essentially the variable x continues to get passed into the collatz function I defined until it gets to 1. However, every time I run the recursive function it prints 'x' repeatedly and then I get the
collatz(3)
'RecursionError: maximum recursion depth exceeded in comparison'
Which I understand is an infinite loop essentially. I thought by reassigning it to x to the results of the first collatz() it would return the new value and continue till it hit '1' but I can't seem to quite get there.
Any help/tips/advice would be great! Thanks!
Recursive functions have what's known as a "base case" and what's known as a "recursive case." The base case is when you should stop recursing and return an answer.
In this case, the base case is when x==1
def collatz(x):
if x == 1:
return x
and the recursive case is the rest of the time
# continuing from above
else:
if n % 2 == 0:
return collatz(int(n//2))
else:
return collatz(n*3 / 2) # sicut. Note that the collatz sequence
# uses 3n+1 here, not 3n/2 as in the question
N.B. that I change the effective value of x in the next loop through collatz before returning the result of that new call. If you don't, and simply return collatz(x), you'll never reach your base case and recurse forever.
#Roee Gavirel
Here is the final answer based on his answer above:
def collatz(x):
if x == 1:
"Done"
elif x%2 == 0:
x = int(x/2)
print(x)
collatz(x)
else:
x = int((3*x)+1)
print(x)
collatz(x)
collatz(3)
Thanks for all the help!
You show two different implementations of the same function collatz, while you need to combine them.
def collatz(n):
if x == 1:
"Done"
print(x)
if n%2 == 0:
collatz(int(n/2))
else:
collatz(int((3 * n)/2))

Name 'absolute value' not defined in Python

So I am really knew to coding, this is problem occurred about 5 minutes after I started. So I am currently doing this Coursera course made by an associate professor at Wesleyan (https://www.coursera.org/learn/python-programming-introduction). One of the exercises was:
Write a function absolutevalue(num) that computes the absolute value of
a number. You will need to use an 'if' statement. Remember if a number is less than zero then you must multiply by -1 to make it greater than zero.
So I figured my answer should be something like this:
absolutevalue(num):
""" Computes the absolute value of a number."""
if num >> 0:
absolutevalue =num
print(absolute value)
elif num<< 0:
absolutevalue == -1*num
print(absolutevalue)
else:
print("Absolute value is 0")
But when I run the code the console keeps saying:
Traceback (most recent call last):
File "", line 1, in
absolutevalue(5)
NameError: name 'absolutevalue' is not defined
For the past hour, I have been trying to fix the problem, yet I don't know how.
Could someone please help me, and keep in mind this is one of my first times trying to code something.
Thanks
A few errors:
Your def statement is missing. Normally a function definition should start with a line like def absolutevalue(num) rather than just absolutevalue(num).
You're using double comparators >> where you should be using single ones >. The former is a bit-shifting operator.
Within the function, you're using a variable with the same name as the function itself: absolutevalue. It's not necessarily wrong, but definitely not particularly handy.
Your function doesn't actually return the absolute value; it just prints it.
Edit: now that your question has been edited to use code blocks: your indentation is missing. :)
Hope that helps!
Function definitions in python need to start with def. Function blocks also need to be indented correctly, for example:
def absolutevalue(num):
""" Computes the absolute value of a number."""
if num > 0:
return num
elif num < 0:
return -1 * num
return 0
print(absolutenumber(-1))
print(absolutenumber(1))
print(absolutenumber(0))
>>> 1
>>> 1
>>> 0
You need to define the function absolutevalue and pass num into it. If you need to return the value instead, use return rather than print()
def absolutevalue(num):
if num > 0:
print(num)
elif num < 0:
abs_value = num * -1
print(abs_value)
else:
print("Absolute value is 0")

Categories