I'm making a refresher on recursion and i've made a python file like this:
#!/usr/bin/python
import sys
if (len(sys.argv)!=3):
raise ValueError('Please provide two dimensions.')
else:
pass
def plotLand(a,b):
if(a==b):
print(a)
return a
if(a<b):
c=b%a
b = c if(c!=0) else a
else:
c = a%b
a = c if (c!=0) else b
plotLand(a,b)
result = plotLand(int(sys.argv[1]),int(sys.argv[2]))
print(result)
I added the print(a)
just to check if my function was returning a value. I call this file in linux terminal in this way:
python algorithms.py 1680 64
And this is my output:
80
None
The print function inside my recursive function is printing the value, but I'm not getting the return value of the function. The original function didn't have the print function, as I mentioned before.
Recursive functions work exactly like non-recursive functions – if you don't write return
and a value, you're returning None
, and you only return anything when a == b
.
You need
return plotLand(a,b)
I also think that you could shorten your code to
def plotLand(a,b):
small, large = sorted((a,b))
remainder = large % small
return plotLand(remainder, small) if remainder else a
You only return for one condition. You can consider adding a default at the end of the function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.