python recursive immediate return [duplicate] - python

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
I am very new python programming , while i write the below code inside the if statement the value of a is determined but , after i return to caller , return value is always none , Is there anything missing to return the value inside an if block on a recursive calls .
#! /usr/bin/env python3
def gcd_calc(a, b):
if(b == 0):
print(a)
return a
c= a%b
gcd_calc(b,c)
if __name__ == "__main__":
a, b = map(int, input().split())
if(a<b):
print(gcd_calc(a,b))
else:
print(gcd_calc(b,a))

You are missing a return
def gcd_calc(a, b):
if(b == 0):
print(a)
return a
c= a%b
return(gcd_calc(b,c)) #you need to return here as you are calling recursively
if __name__ == "__main__":
a, b = map(int, input().split())
if(a<b):
print(gcd_calc(a,b))
else:
print(gcd_calc(b,a))

Related

Python: Choose function based on condition in a for loop?

Sorry if the title is a little vague. I'll explain everything in greater detail here. So let's say I have this code:
def function1(k):
return k * 2
def function2(k):
return k ** 2
func = 'Square'
for i in range(1, 10):
if func == 'Multiply':
function1(i)
elif func == 'Square':
function2(i)
How can I modify the code above so that the if statement can go outside the loop? It seems unnecessary to check in every iteration the value of func since it's not going to change inside. the loop. What I'm looking for is something like this:
def function1(k):
return k * 2
def function2(k):
return k ** 2
func = 'Square'
if func == 'Multiply':
f = function1()
elif func == 'Square':
f = function2()
for i in range(1, 10):
f(i)
Let me know if something isn't clear enough or if what I'm asking isn't possible.
Store the function in a dict, then you can skip the if statements.
def function1(k):
return k * 2
def function2(k):
return k ** 2
d = {"Multiply": function1, "Square": function2}
func = "Square"
f = d[func]
f(3)
# 9
You can do this:
funcs = {'Multiply':function1, 'Square':function2}
theFunc = funcs[func]
for i in range(1, 10):
x = theFunc(i)
print(x)
One note in passing: the ^ operator is not taking the square of the argument, but rather performing bitwise xor on it.

How to compose a list of functions to a callable [duplicate]

This question already has answers here:
Composing functions in python
(16 answers)
Closed 5 years ago.
I have a simple source.
def h(x):
return x + 1
def m(x):
return x + 2
def n(x):
return x * 10
def function_aggregator(fun_list, num):
return_fun = None
for fun in fun_list[::-1]:
if return_fun:
return_fun = fun(return_fun)
else:
return_fun = fun(num)
return return_fun
if __name__ == "__main__":
lst = [h, m, n]
y = function_aggregator(lst, 4)
print(y)
Is there any way to make the function_aggregator method receive just the list and return a callable the will be the same as h(m(n(<any_number>))
The previous answer is pretty close. The exact answer is:
def function_aggregator(fun_list):
def wrapper(arg):
for fun in reversed(fun_list):
arg = fun(arg)
return arg
return wrapper
if __name__ == "__main__":
lst = [g, f, n, m, h]
p = function_aggregator(lst)
x = 3
print("p(x): {}".format(p(x)))
Thanks to Zero Piraeus commet
It could be done using closure:
def function_aggregator(*func_list):
def aggregate(num):
for func in reversed(func_list):
num = func(num)
return num
return aggregate
if __name__ == "__main__":
myfunc = function_aggregator(h, m, n)
print(myfunc(4))
Notes
function_aggregator now takes an arbitrary number of functions
Inside, it defines another function, aggregate, this is the callable you are talking about.
function_aggregator returns that callable, AKA aggregate to the caller
The caller then give it a name, myfunc in this case
From then on, we can treat myfunc as a function which takes 1 argument and return something

Python BST code returning None instead of array? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
The following code returns None on some values (eg 306, 136), on some values (42, 84), it returns the answer correctly. The print a and return a should yield the same result, but it does not:
def gcdIter (a,b):
c = min (a,b)
d = max (a,b)
a = c
b = d
if (b%a) == 0:
print a
return a
gcdIter (a,b%a)
print gcdIter (a,b)
You are ignoring the return value for the recursive call:
gcdIter (a,b%a)
Recursive calls are no different from calls to other functions; you'd still need to do something with the result of that call if that is what you tried to produce. You need to pass on that return value with return
return gcdIter (a,b%a)
Note that you can assign to multiple targets when assigning:
def gcdIter(a, b):
a, b = min(a, b), max(a, b)
if b % a == 0:
return a
return gcdIter(a, b % a)
You really don't need to care about the bigger and smaller values here. A more compact version would be:
def gcd_iter(a, b):
return gcd_iter(b, a % b) if b else abs(a)

How do I use multiple variable from one function into another? [duplicate]

This question already has answers here:
Alternatives for returning multiple values from a Python function [closed]
(14 answers)
Closed 9 months ago.
When I try to call a, b in function add, I get a is not defined even though I am returning the values. How do I make it return both a and b?
def numbers():
a= input ("a:")
a = int(a)
b= input ("b:")
b = int(b)
return a
return b
def add():
numbers()
print (a)
print (b)
add()
A return statement almost always causes a function to immediately terminate, and no other statement in the function will run. So once you return a, you'll never get to return b. You need to return both of them at the same time.
Additionally, returning a value from a function will not automatically put those names into the scope that called the function. You need to manually assign the values to something.
def numbers():
a= input ("a:")
a = int(a)
b= input ("b:")
b = int(b)
return a,b
def add():
a,b = numbers()
print (a)
print (b)
add()
I think so:
def numbers():
a= input ("a:")
a = int(a)
b= input ("b:")
b = int(b)
return a, b
def add(a, b):
print (a)
print (b)
return a, b
def main():
another_a, another_b = numbers()
another_a, another_b = add(another_a, another_b)
main()

Why Python recursive function returns None [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
The following code returns None on some values (eg 306, 136), on some values (42, 84), it returns the answer correctly. The print a and return a should yield the same result, but it does not:
def gcdIter (a,b):
c = min (a,b)
d = max (a,b)
a = c
b = d
if (b%a) == 0:
print a
return a
gcdIter (a,b%a)
print gcdIter (a,b)
You are ignoring the return value for the recursive call:
gcdIter (a,b%a)
Recursive calls are no different from calls to other functions; you'd still need to do something with the result of that call if that is what you tried to produce. You need to pass on that return value with return
return gcdIter (a,b%a)
Note that you can assign to multiple targets when assigning:
def gcdIter(a, b):
a, b = min(a, b), max(a, b)
if b % a == 0:
return a
return gcdIter(a, b % a)
You really don't need to care about the bigger and smaller values here. A more compact version would be:
def gcd_iter(a, b):
return gcd_iter(b, a % b) if b else abs(a)

Categories

Resources