Skip to content

Instantly share code, notes, and snippets.

@TristynAlxander
Created October 17, 2023 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TristynAlxander/ee6e7dabe2a57c983b7f617df61f2c1e to your computer and use it in GitHub Desktop.
Save TristynAlxander/ee6e7dabe2a57c983b7f617df61f2c1e to your computer and use it in GitHub Desktop.
Function defines the longest similar sequence between given iterables.
def find_longest_similar(a,b,is_similar=None,is_ignored = None):
'''
This function defines the longest similar sequence between given iterables.
If no similarity function is given the function uses equality.
'''
# Default Functions
if(not is_similar): is_similar = lambda x,y: x==y
if(not is_ignored): is_ignored = lambda _:False
# Default Values
a_best, b_best, size_best = 0, 0, -1
a_start,b_start = 0,0
matching,match_index = False,-1
for i,a_i in enumerate(a):
if(is_ignored(a_i)): continue
for j,b_j in enumerate(b):
if(j <= match_index): continue
if(is_ignored(b_j)): continue
# Compare
if(is_similar(a_i,b_j)):
# Starting Match
if(not matching): a_start,b_start = i,j
# Exit Actions
matching,match_index = True,j
break
else:
# Ending Match
if(matching and size_best < i - a_start):
size_best = i - a_start
a_best,b_best = a_start,b_start
# Exit Actions
matching,match_index = False,-1
# Ending Match
if(matching and size_best < len(a) - a_start):
size_best = len(a) - a_start
a_best,b_best = a_start,b_start
# Return
return (a_best, b_best, size_best)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment