The ratio() method of SequenceMatcher class

Overview:

  • The ratio() method of the SequenceMatcher class computes and returns the similarity ratio of two sequences. The value of the similarity ratio varies from 0 to 1
  • When two sequences are exactly same the similarity ratio between them is 1. For two sequences that are completely different the similarity ratio is 0. When some of the elements present in the sequences match the similarity ratio is greater than 0 and less than 1.
  • If calls have been already made to the functions get_matching_blocks() or get_opcodes(), a call to the ratio() function returns faster. Otherwise, the ratio() function takes relatively long time to compute the similarity ratio.

Example:

# Example Python program that computes the ratio

# of similarity between two sequences using the

# ratio() method of the SequenceMatcher class

 

import difflib

 

# Create an instance of SequenceMatcher

seqMatcher = difflib.SequenceMatcher()

 

# Set two sequences that are mostly similar

seq1 = "O my Luve is like a red, red rose"

seq2 = "O my Luve is like the melody"

 

seqMatcher.set_seq1(seq1)

seqMatcher.set_seq2(seq2)

 

# Compute the similarity ratio

similarityRatio = seqMatcher.ratio()

print("Similarity ratio of two sequences:")

print(similarityRatio)

 

# Set two sequences that are exactly the same

seqMatcher.set_seq1("Hello World")

seqMatcher.set_seq2("Hello World")

similarityRatio = seqMatcher.ratio()

print("Similarity ratio of two sequences which are same:")

print(similarityRatio)

 

# Set two sequences that are completely different

seqMatcher.set_seq1("abc")

seqMatcher.set_seq2("def")

similarityRatio = seqMatcher.ratio()

print("Similarity ratio of two sequences that completely different:")

print(similarityRatio)

Output:

Similarity ratio of two sequences:
0.6885245901639344
Similarity ratio of two sequences which are same:
1.0
Similarity ratio of two sequences that completely different:
0.0

 


Copyright 2026 © pythontic.com