Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].
Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = “makes”, word2 = “coding”, return 1.
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))
Input_1:
Enter the string : fcuk the code . com
Enter word1 : fcuk
Enter word2 : code
Output:
2
Input_2:
Enter the string : eat code sleep repeat
Enter word1 : code
Enter word2 : sleep
Output:
1
Input_3:
Enter the string : practice makes perfect coding makes
Enter word1 : coding
Enter word2 : practice
Output:
3
Input_4:
Enter the string : practice makes perfect coding makes
Enter word1 : makes
Enter word2 : coding
Output:
1
Demo Output:
More Q
- Find the majority element appearing more than n/2 times
- Return an array of the squares of each number.
- Highest factor in addition.
- Find the empty packets(0) of chocolate and push it to the end of the conveyor belt(array).
- Every element in array appears twice.Find that single one.
- Find the duplicate letters in string. Same to do in dictionary way.
- Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.
- Return the maximum number you can get by changing at most one digit.
- Sed Commands – Ranges of lines.
- Find the kth smallest element in the given 2D array.
- Find all elements that appear more than [n/3] times.
- Write a function to return true if s2 contains the permutation of s1.
- Sort the array into a wave like array.
- Re-order array, such that
nums[0] < nums[1] > nums[2] < nums[3]...
. - Given the coordinates, return true if the four points construct a square.
- Minimum Distance Between Words of a String.
- Return the shortest distance between these two words.
- Write a program to find the n-th ugly number.
- Check if array could become Non – Decreasing array.
- Find the minimum area of a rectangle that can be formed from given points.