I want to find the larger of two integers. But I have to use Recursion and without python operators. Code structure is given below.
def gt(a, b):
'''Returns True if a is an integer greater than b;
returns False otherwise'''
# using only incr, decr, zero, and recursion
return 0
def incr(a):
'''Returns the next integer after a'''
return a 1
def zero(a):
'''Returns True if a is zero'''
return a == 0
def decr(a):
'''Returns the integer before a'''
return a - 1
CodePudding user response:
version for positive integers
You could decrement both numbers and see whether a or b reaches zero first:
def gt(a, b):
'''Returns True if a is an integer greater than b;
returns False otherwise'''
# using only incr, decr, zero, and recursion
if zero(b) and not zero(a):
return True
if zero(a):
return False
return gt(decr(a), decr(b))
examples:
>>> gt(100, 10)
True
>>> gt(10, 10)
False
>>> gt(1, 10)
False
CodePudding user response:
If you are permitted the simplest of loops (using only zero
for the breaking condition):
def gt(a, b):
# 1. get a to zero by going up and down in parallel
aup = adown = a
bup = bdown = b
while True:
if zero(aup):
a, b = aup, bup
break
if zero(adown):
a, b = adown, bdown
break
aup, adown = incr(aup), decr(adown)
bup, bdown = incr(bup), decr(bdown)
if zero(b):
return False
# 2. get b to zero
bup = bdown = b
while True:
if zero(bup):
return True
if zero(bdown):
return False
bup, bdown = incr(bup), decr(bdown)