python统计字符出现次数递归_递归函数,用于计算数字中数字的出现次数(python)...

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值