The first and last occurrence. Given a string that may or may not contain the letter “f”, print the index location of the first and last appearance of “f”. If the letter “f” occurs only once, print its index. If the letter “f” does not occur, do not print anything. Do not use loops in this task.
|
s = input() first_index = s.find('f') last_index = s.rfind('f') if first_index != -1: if first_index == last_index: print(first_index) else: print(first_index) print(last_index) |
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 and Last Index of ‘f’:
first_index = s.find('f')
last_index = s.rfind('f')
- The
find('f')
method returns the index of the first occurrence of ‘f’. If ‘f’ is not found, it returns -1.
- The
rfind('f')
method returns the index of the last occurrence of ‘f’. If ‘f’ is not found, it returns -1.
- Printing the Indices:
|
if first_index != -1: if first_index == last_index: print(first_index) else: print(first_index) print(last_index) |
If first_index
is not -1 (meaning ‘f’ is found at least once):
- If
first_index
is equal to last_index
, ‘f’ occurs only once, so print first_index
.
- Otherwise, print both
first_index
and last_index
.