Open In App

Python | Find all close matches of input string from a list

Last Updated : 31 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. Examples:

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.

Python3




# Function to find all close matches of
# input string in given list of possible strings
from difflib import get_close_matches
 
def closeMatches(patterns, word):
     print(get_close_matches(word, patterns))
 
# Driver program
if __name__ == "__main__":
    word = 'appel'
    patterns = ['ape', 'apple', 'peach', 'puppy']
    closeMatches(patterns, word)


References : https://docs.python.org/2/library/difflib.html 

Output:

['apple', 'ape']

Time complexity : O(n*m), where n is the number of elements in the input list patterns, and m is the length of the input string word. The reason for this is that the get_close_matches() function from the difflib library uses a dynamic programming algorithm to find approximate matches, which can take O(nm) time. 

Space complexity :  O(n), as it only uses a fixed amount of memory, regardless of the size of the input string.


Similar Reads

Python | Check if suffix matches with any string in given list
Given a list of strings, the task is to check whether the suffix matches any string in the given list. Examples: Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output: TrueInput: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output: False Let's discuss a few methods to do the task. Method #1: Using any() The most concise and read
6 min read
Python | Check if string matches regex list
Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let's discuss a way in which this task can be performed. Method : Using join regex + loop + re.match() This task can be performed using combination of above functions. In this, we cre
4 min read
Python NumPy - Return real parts if input is complex with all imaginary parts close to zero
In this article, we will discuss how to return real parts if the input is complex with all imaginary parts close to zero in Python. The numpy np.real_if_close() method is used to return the real parts if the input is a complex number with all imaginary parts close to zero. “Close to zero” is defined as tol * (machine epsilon of the type for a). syn
2 min read
Python | Program that matches a word containing 'g' followed by one or more e's using regex
Prerequisites : Regular Expressions | Set 1, Set 2 Given a string, the task is to check if that string contains any g followed by one or more e's in it, otherwise, print No match. Examples : Input : geeks for geeks Output : geeks geeks Input : graphic era Output : No match Approach : Firstly, make a regular expression (regex) object that matches a
2 min read
Python - Extract Indices of substring matches
Given a String List, and a substring, extract list of indices of Strings, in which that substring occurs. Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" Output : [0, 2, 3] Explanation : "Gfg" is present in 0th, 2nd and 3rd element as substring. Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg"
5 min read
Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 min read
Close specific Web page using Selenium in Python
Prerequisites: Selenium Basics, Selenium close() and quit() Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. The close() meth
2 min read
Python | os.close() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.close() method in Python is used to close the given file descriptor, so that it no longer refers to any file or other resource a
2 min read
response.close() - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.close() out of a
2 min read
How to use close() and quit() method in Selenium Python ?
While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the driver.dispose method that successively closes all the
2 min read
Practice Tags :
three90RightbarBannerImg