Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

greatest common divisor for strings in python

I would like to have a python function that given the list

mystrings = ['abcde', 'abcdf', 'abcef', 'abcnn']

returns the string 'abc', i.e., the longest piece contained by all the elements in the list. I have a solution which just loops through the slices of mystring[0], and compares it to the rest, and breaks out of the loop, whenever the first unmatching substring is found. However, I suspect that there must be a more efficient, elegant, and pythonic way of doing this.

Could someone point out how to do this properly?

like image 657
v923z Avatar asked Aug 17 '26 12:08

v923z


1 Answers

The way you described, you want the biggest substring at the starting point:

>>> os.path.commonprefix(['abcde', 'abcdf', 'abcef', 'abcnn'])
'abc'
like image 179
JBernardo Avatar answered Aug 19 '26 02:08

JBernardo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!