递归函数,用于计算某个序列出现的次数

我正在编写一个递归函数,该函数将整数作为输入,它将返回整数中出现123的次数。


例如:


打印(一二三(123123999123))


将打印出 3,因为序列 123 在我输入到函数中的数字中出现 3 次。


这是我到目前为止的代码:


def onetwothree(x):

    count = 0

    while(x > 0):

        x = x//10

        count = count + 1

    if (count < 3):  #here i check if the digits is less than 3, it can't have the sequence 123 if it doesn't have 3 digits

        return 0

    if (x%10==1 and x//10%10 == 2 and x//10//10%10==3):

        counter += 1

    else:

        return(onetwothree(x//10))

这会继续打印“0”。


慕田峪4524236
浏览 147回答 2
2回答

慕标琳琳

我认为你过度思考递归。像这样的解决方案应该有效:def onetwothree(n, count=0):&nbsp; &nbsp; if n <= 0:&nbsp; &nbsp; &nbsp; &nbsp; return count&nbsp; &nbsp; last_three_digits = n % 1000&nbsp; &nbsp; n_without_last_number = n // 10&nbsp; &nbsp; if last_three_digits == 123:&nbsp; &nbsp; &nbsp; &nbsp; return onetwothree(n_without_last_number, count + 1)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return onetwothree(n_without_last_number, count)print(onetwothree(123123999123))输出:3

拉丁的传说

如果要计算数字中“123”出现的次数,为什么不将数字从整数转换为字符串并使用?str.count然后你的函数将如下所示:def&nbsp;onetwothree(x): &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;str(x).count('123')但它也不再是递归的。您也可以只使用与函数一起使用几乎相同的行。print(str(123123999123).count('123'))onetwothree我希望这个答案对:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python