mardi 18 février 2020

Recursion function to count how many times a certain sequence appears

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".

Aucun commentaire:

Enregistrer un commentaire