How to return void in python - 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,"")

Related

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)

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

How does return terminate all instances of a recursion in Python

How does return terminates all the instances in a recursion? In the following it seems to me that the only time the return statement is called is in the base case and yet it seems to close all of the other instances where n is > 1.
def reco(n):
print('create instance nbr ', n)
if n == 1:
print('base case reached, instances will be popped LIFO')
return
else:
n -= 1
reco(n)
print('pop instance nbr ', n)
n = 5
reco(n)
You're right, the return statement only executes once, but the reco() call is the second-to-last statement in all the other instances. The execution just falls out the end of the other instances.
It might help if you imagined that every function body has an implicit return None statement at the end.

Recursive function of the product of a list not working

I'm trying to create a function that multiplies each item in a list and returns the total. The function doesn't stop running until memory runs out.
Can someone please explain to me why this isn't working?
items = [1,2,3,4,10]
def mult2(items):
if not items:
return 0
return mult2(items[0]) * mult2(items[1:])
mult2(items)
Couple of mistakes here
Your base case is wrong. The Base case has to be when the list is reduced to a single element and you need to return 1 and not 0.
You need to send a list with a single element and not the single element alone to meet your base case.
Corrected code
def mult2(items):
if len(items)==1:
return items[0]
return mult2([items[0]]) * mult2(items[1:])
Demo
>>> items = [1,2,3,4,10]
>>>
>>> def mult2(items):
... if len(items)==1:
... return items[0]
... return mult2([items[0]]) * mult2(items[1:])
...
>>> print(mult2(items))
240
There are two issues:
Single element is passed to mult2, but sequence is expected. That's why TypeError: 'int' object has no attribute '__getitem__' is raised, due to trying to subscripting int (code being executed resolves to 1[1:] which is simply not possible).
Your exit condition is broken. Neutral multiplier is 1, not 0.
After fixes your code would look like this:
def mult2(seq):
if not seq:
return 1
return seq[0] * mult2(seq[1:])
items = [1,2,3,4,10]
assert 240 == mult2(items)
You don't have a base case for your recursion that works properly.
Consider calling mult2 with [1,2,3] this gets to the return statement which called mult2 with 1 and with [1,2].
The problem is in the call to mult2 with the parameter 1 which is just an integer. When you get to the recursive part there's no indexing available because items is just an int at this point, so items[0] and items[1:] don't make sense at this point.
Fixed the errors in the OP, and this works:
items = [1,2,3,4,10]
def mult2(items):
if len(items) == 1:
return items[0]
return items[0] * mult2(items[1:])
print "sum:",mult2(items)

function is not getting called in python

Hi i am new to Python programming . I am writing a python code which uses stack.
There are two function in my python code isdesc() and poisonplant()
When i have called the function poisonplant in there is another function but that function is not get called
Code is indented properly
Here is my code:
def isdesc(arr):
if len(arr) == 0:
return False
for i in range(0,len(arr)):
if arr[i+1] < arr[i]:
return True
else:
return False
def poisonplant(expr):
count=0
pdb.set_trace()
while not isdesc(expr):
s.push(expr[0])
for i in range(0,len(expr)):
if expr[i+1] < expr[i]:
s.push(expr[i+1])
count+=1
del expr[:]
for each_item in s.items:
a=s.pop()
expr.insert(0,a)
return count
input1=[6,5,8,4,7,10,9]
print(poisonplant(input1))
I have only called poisonplant and i think isdec is automatically get called inside poison function.
Can someone help me in this why isdesc is not get called here
isdesc is returning too soon, without looking at all the adjacent elements. It should read
def isdesc(arr):
for i in range(len(arr)-1):
if arr[i] < arr[i+1]:
return False
return True
(I've slightly modified the definition to treat empty lists as descending. If you treat an empty list as non-descending, you'll enter the loop, where you are assuming the list is not empty.)
Your main problem is that you're using return as if it will return each iteration, but you're actually just going to return on the very first one. You could instead return False if any of the sorts are wrong, but a better way to check if the lists are sorting in descending order is to check if the list is equal to a reverse sort of itself.
def isdesc(arr):
if len(arr) == 0:
return False
return arr == sorted(arr, reverse=True)

Categories