In: Computer Science
Given a string sentence that consists of some words separated by a single space, and a string searchWord.
Write a function isPrefix to check if searchWord is a prefix of any word in sentence. A prefix of a string S is any leading contiguous substring of S. It returns the index of the word in sentence where searchWord is a prefix of this word (1-indexed).
If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.
Input: sentence = this problemo is an easy problemo, searchWord = pro
Output: 2
Explanation: pro is prefix of problemo which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
Solution:
#function to check weather the word in sentence has prefix as
searchWord
def isPrefix(string,searchWord):
#converting
the words in a given string in the form of list separated by
spaces
lis=list(string.split(" "))
#iterating
through all the elements of list
for i in lis:
#startswith( ) checks weather
the element starts with searchWord
if i.startswith(searchWord):
#if the word
starts with the searchWord then its index is returned
return lis.index(i)+1
#in case there is no
word in list that starts with searchWord then return -1
return -1
#taking string as input from user
string=input("Enter the string :")
#taking searchWord as input from user
searchWord=input("Enter the prefix word to be searched
:")
#calling function isPrefix to get the required result
print(isPrefix(string,searchWord))
Steps to solve :
Note: if you find any error in the above code it may be due to improper indentation ,so please provide proper indentation with the help of above image
If you find my answer helpful please give thumbs up .thank you