Recursion function to count how many times a certain sequence appears

Freelance Video and Photo Edit :

I am writing a recursive function that takes an integer as input and it will return the number of times 123 appears in the integer.

So for example:

print(onetwothree(123123999123))

Will print out 3 because the sequence 123 appears 3 times in the number I entered into the function.

Here is my code so far:

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))

This keeps printing "0".

Felipe :

I think you are overthinking recursion. A solution like so should work:

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))

Outputs:

3

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198227&siteId=1