Menu Close

Minimum Distance Between Words of a String.

Given a string s and two words w1 and w2 that are present in S. The task is to find the minimum distance between w1 and w2. Here distance is the number of steps or words between the first and the second word.
Examples:

Input : S = “Fcuk The Code”, W1 = “Fcuk”, W2 = "Code” 
Output : 1 
There is only one word between closest occurrences of W1 and W2.
Input : S = “FcukTheCode Online Code Eat Sleep Repeat”, W1 = “Online”, W2 = “Sleep” 
Output : 2
list=input('Enter the string : ').split(' ')
word1=input('Enter word1 : ')
word2=input('Enter word2 : ')
pos1=None
pos2=None
for i in range(len(list)):
	if list[i] == word1 :
		pos1=i
	if list[i] == word2 :
		pos2=i
if pos1 == None or pos2 == None :
	print(0)
else:
	print(abs(pos1-pos2)-1)

Input_1:
Enter the string : Fcuk The Code
Enter word1 : Fcuk
Enter word2 : Code

Output:
1


Input_2:
Enter the string : FcukTheCode Online Code Eat Sleep Repeat
Enter word1 : Online
Enter word2 : Sleep

Output:
2


Input_3:
Enter the string : I will be the king of pirates
Enter word1 : will
Enter word2 : pirates

Output:
4


Demo Output:

Executed python 3 using Linux Terminal

More Q