[英]How to find larger of two integers using recursion and not using operators in python
I want to find the larger of two integers.我想找到两个整数中较大的一个。 But I have to use Recursion and without python operators.但我必须使用递归而不使用 python 运算符。 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
You could decrement both numbers and see whether a or b reaches zero first:您可以减少两个数字,然后查看 a 或 b 是否先达到零:
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
If you are permitted the simplest of loops (using only zero
for the breaking condition):如果允许您使用最简单的循环(仅使用zero
作为中断条件):
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.