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

2024-09-27 00:21:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

打印(一张三张(123999123))

将打印出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”


Tags: andthe函数代码returnifhavecount
2条回答

我认为你在过度思考递归。这样的解决方案应该有效:

def onetwothree(n, count=0):
    if n <= 0:
        return count

    last_three_digits = n % 1000
    n_without_last_number = n // 10

    if last_three_digits == 123:
        return onetwothree(n_without_last_number, count + 1)
    else:
        return onetwothree(n_without_last_number, count)

print(onetwothree(123123999123))

产出:

3

如果要计算一个数字中出现“123”的次数,为什么不将数字从整数转换为字符串并使用str.count

那么您的函数将如下所示:

def onetwothree(x):
    return str(x).count('123')

但它也不再是递归的

您也可以只使用print(str(123123999123).count('123'))行,这与使用onetwothree函数几乎相同

我希望这个答案有帮助:)

相关问题 更多 >

    热门问题