def oneCount(n):
n = str(n)
# Here, you check if the entire string is '1'.
# Not sure if you mean to check if a single digit is '1'.
if n == '1':
return 1
else:
# If the entire string is not '1', you recur on all but the least significant digit.
return 1 + oneCount(n[:-1])
print oneCount(1100)
步行:oneCount(1100) -> '1100' is not '1'. recurs on 1 + oneCount('110')
1 + oneCount('100') -> '110' is not '1'. recurs on 1 + (1 + oneCount('11'))
2 + oneCount('00') -> '11' is not '1'. recurs on 2 + (1 + oneCount('1'))
3 + oneCount('0') -> '1' is '1'. return 1
4
好吧,那是个错误的答案,但也许更隐晦的是,如果你最重要的数字不是1呢?oneCount(2)
>>> RuntimeError: maximum recursion depth exceeded while calling a Python object
你在空字符串上重复出现。空字符串不是“1”,因此递归是无限的!
当在iterable(如字符串或列表)上重复出现时,一个好的经验法则是将空的iterable视为基本大小写。def oneCount(i):
i = str(i)
if i == '':
return 0
# Do not recur in the base case, above
# The below cases are not the base case, so expect to recur
# What is the nature of the recursion?
car, cdr = i[0], i[1:] # silly lisp reference
if car == '1':
???
# else?
只是为了好玩
布尔值作为整数
假设在Python中,布尔值等于1或0的整数值。可以将该值添加到整数中。return (car == 1) + oneCount(cdr)
根
考虑到不需要将整数转换为字符串就可以遍历它。考虑一下cdr, car = divmod(i, 10),或者更简单地说,cdr, car = i // 10, i % 10。有趣的是,它让你能够计算数字在任何基数中的出现次数。def oneCount(i, base=10):
if i == 0:
return 0
cdr, car = divmod(i, base)
if car == 1:
???
???
>>> oneCount(int('111111100000', 2), 2)
7