[英]How to find larger of two integers using recursion and not using operators in python
我想找到兩個整數中較大的一個。 但我必須使用遞歸而不使用 python 運算符。 代碼結構如下。
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
您可以減少兩個數字,然后查看 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))
例子:
>>> gt(100, 10)
True
>>> gt(10, 10)
False
>>> gt(1, 10)
False
如果允許您使用最簡單的循環(僅使用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.