Exercise 77

Create a Python algorithm that identifies the initial index of a specified occurrence within a provided string, 's', without relying on any built-in methods like find() or rfind(). If the occurrence is not present in the string 's', the algorithm should return -1.
For instance : if 's' = "Python programming language" and the target occurrence = "prog" the algorithm should return 7.

Solution

def custom_find(s, occ):
    s_len = len(s)
    occ_len = len(occ)

    for i 
     
    <p style="text-align: right;"><strong>Younes Derfoufi</strong>
    <strong>CRMEF OUJDA</strong></p>
    in range(s_len - occ_len + 1):
        if s[i:i + occ_len] == occ:
            return i

    return -1

# Example usage:
s = "Python programming language"
occurrence = "prog"
result = custom_find(s, occurrence)

print(result) # output : 7




 

Younes Derfoufi
CRMEF OUJDA

One thought on “Solution Exercise 77 : Custom Occurrence Finder Challenge in Python”

Leave a Reply