我正在编写一个递归函数,它接受一个整数作为输入,它将返回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”
我认为你在过度思考递归。这样的解决方案应该有效:
产出:
如果要计算一个数字中出现“123”的次数,为什么不将数字从整数转换为字符串并使用
str.count
那么您的函数将如下所示:
但它也不再是递归的
您也可以只使用
print(str(123123999123).count('123'))
行,这与使用onetwothree
函数几乎相同我希望这个答案有帮助:)
相关问题 更多 >
编程相关推荐