We are given a list of pattern strings and a single input string. We need to find all possible close good enough matches of input string into list of pattern strings.
Input : patterns = ['ape', 'apple', 'peach', 'puppy'], input = 'appel' Output : ['apple', 'ape']
We can solve this problem in python quickly using in built function difflib.get_close_matches().
How does difflib.get_close_matches() function work in Python ?
difflib.get_close_matches(word, possibilities, n, cutoff) accepts four parameters in which n, cutoff are optional. word is a sequence for which close matches are desired, possibilities is a list of sequences against which to match word. Optional argument n (default 3) is the maximum number of close matches to return, n must be greater than 0. Optional argument cutoff (default 0.6) is a float in the range [0, 1]. Possibilities that don’t score at least that similar to word are ignored.
The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first.
References : https://docs.python.org/2/library/difflib.html
- Python | Check if string matches regex list
- Python | Check if suffix matches with any string in given list
- Python | Get a list as input from user
- Python | Convert list of string to list of list
- Python | Convert list of string into sorted list of integer
- Python | Convert list of numerical string to list of Integers
- Python | Convert a string representation of list into list
- Python | Convert string enclosed list to list
- Python | Check if given string can be formed by concatenating string elements of list
- Python | os.close() method
- Python | Check if string ends with any string in given list
- Python | Program that matches a word containing 'g' followed by one or more e's using regex
- Python | Find maximum length sub-list in a nested list
- Generate two output strings depending upon occurrence of character in input string in Python
- Sum of list (with string types) in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.