Python 如何理解二进制表示函数的递归
我跟踪了以下代码,其中一部分对我来说没有意义:Python 如何理解二进制表示函数的递归,python,recursion,Python,Recursion,我跟踪了以下代码,其中一部分对我来说没有意义: def bin_rep(n: int) -> str: """Return the binary representation of n >>> bin_rep(0) "0" >>> bin_rep(1) "1" >>> bin_rep(5) "101" """ if n > 1:
def bin_rep(n: int) -> str:
"""Return the binary representation of n
>>> bin_rep(0)
"0"
>>> bin_rep(1)
"1"
>>> bin_rep(5)
"101"
"""
if n > 1:
return bin_rep(n // 2) + bin_rep(n % 2)
else:
return str(n)
我不明白的是,为什么我们要添加
bin_rep(n//2)
和bin_rep(n%2)
。我知道没有加法是行不通的,但我不明白为什么会有加法。那不是加法bin_rep
返回一个字符串。类型字符串的+
运算符是串联运算符。把这个读作
binary representation of n right-shifted a bit
concatenated with
binary representation of n's right-most bit
这就清楚了吗?这不是加法
bin_rep
返回一个字符串。类型字符串的+
运算符是串联运算符。把这个读作
binary representation of n right-shifted a bit
concatenated with
binary representation of n's right-most bit
这会清除它吗?bin_rep(n)
返回n
的二进制字符串表示形式
终止条件为n'0'
或bin_rep(1)->“1”
bin\u rep(2)
必须返回'10'
。为此,它计算:
bin_rep(2 // 2) + bin_rep(n % 2)
bin_rep(1) + bin_rep(0)
'1' + '0' # String concatenation, not decimal addition!
'10'
。。。这是正确的答案。这应该有助于澄清您的理解。bin_rep(n)
返回n
的二进制字符串表示形式
终止条件为n'0'
或bin_rep(1)->“1”
bin\u rep(2)
必须返回'10'
。为此,它计算:
bin_rep(2 // 2) + bin_rep(n % 2)
bin_rep(1) + bin_rep(0)
'1' + '0' # String concatenation, not decimal addition!
'10'
。。。这是正确的答案。这应该有助于澄清您的理解。因为
bin_rep
总是返回一个字符串,所以这是一个字符串串联,而不是一个加法。这对您有帮助吗?因为bin_rep
总是返回一个字符串,所以这是一个字符串串联,而不是一个加法。这对你有帮助吗?非常感谢,这帮了我很多忙!非常感谢,这对我帮助很大!