If I have an input string and an array:
s = "to_be_or_not_to_be"
pos = [15, 2, 8]
I am trying to find the longest common prefix between the consecutive elements of the array pos referencing the original s. I am trying to get the following output:
longest = [3,1]
The way I obtained this is by computing the longest common prefix of the following pairs:
s[15:]which is_beands[2:]which is_be_or_not_to_begiving 3 (_be)s[2:]which is_be_or_not_to_beands[8:]which is_not_to_begiving 1 (_)
However, if s is huge, I don’t want to create multiple copies when I do something like s[x:]. After hours of searching, I found the function buffer that maintains only one copy of the input string but I wasn’t sure what is the most efficient way to utilize it here in this context. Any suggestions on how to achieve this?
Here is a method without
bufferwhich doesn’t copy, as it only looks at one character at a time:I use
islice,izip, andxrangein case you’re talking about potentially very long strings.I also couldn’t resist this “One Liner” which doesn’t even require any indexing:
One final method, using
os.path.commonprefix: