The second occurrence. Given a string that may or may not contain the letter “f”, print the index location of the second occurrence of the letter “f”. If the string contains the letter “f” only once, print -1. If the string does not contain the letter “f”, print -2.
|
s = input() # Find the first occurrence of 'f' first_index = s.find('f') # Find the second occurrence of 'f' by searching from the index after the first occurrence second_index = s.find('f', first_index + 1) # Determine the output based on the presence of 'f' in the string if second_index != -1: print(second_index) elif first_index != -1: print(-1) else: print(-2) |
Explanation of the Code
- Reading Input:
- The
input()
function reads a line of text from the user and stores it in the variable s
.
- Finding the First Occurrence of ‘f’:
first_index = s.find('f')
- The
find('f')
method returns the index of the first occurrence of ‘f’. If ‘f’ is not found, it returns -1.
- Finding the Second Occurrence of ‘f’:
second_index = s.find('f', first_index + 1)
- The
find('f', first_index + 1)
method searches for ‘f’ starting from the index just after the first occurrence.
- Determining the Output:
|
if second_index != -1: print(second_index) elif first_index != -1: print(-1) else: print(-2) |
- If
second_index
is not -1, it means there is a second occurrence of ‘f’, so it prints second_index
.
- If
second_index
is -1 but first_index
is not -1, it means ‘f’ occurs only once, so it prints -1.
- If both
first_index
and second_index
are -1, it means ‘f’ does not occur at all, so it prints -2.