gpt4 book ai didi

python - 递归函数计算某个序列出现的次数

转载 作者:行者123 更新时间:2023-11-30 21:50:42 26 4
gpt4 key购买 nike

我正在编写一个递归函数,它接受一个整数作为输入,它将返回 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”。

最佳答案

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

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

关于python - 递归函数计算某个序列出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60291631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com