How to replace all instances of a sub-sequence in a list in Python?

2024/9/21 16:29:35

I currently use this code:

""" Replace all occurrences of subsequence a with b in list l """ 
def replace_subsequence(l,a,b):for i in range(len(l)):if(l[i:i+len(a)] == a):l[i:i+len(a)] = b

Example:

>>> l = [1,2,3]
>>> replace_subsequence(l,[2,3],[4])
>>> l
[1, 4]

Is there a more efficient and/or elegant way to do this ?

Answer

To improve efficiency, you can use the Boyer–Moore string search algorithm when searching for a sublist in a list

Code (credits)

def match(pattern, list):matches = []m = len(list)n = len(pattern)rightMostIndexes = preprocessForBadCharacterShift(pattern)alignedAt = 0while alignedAt + (n - 1) < m:for indexInPattern in xrange(n-1, -1, -1):indexInlist = alignedAt + indexInPatternx = list[indexInlist]y = pattern[indexInPattern]if indexInlist >= m:breakif x != y:r = rightMostIndexes.get(x)if x not in rightMostIndexes:alignedAt = indexInlist + 1else:shift = indexInlist - (alignedAt + r)alignedAt += (shift > 0 and shift or alignedAt + 1)breakelif indexInPattern == 0:matches.append(alignedAt)alignedAt += 1return matchesdef preprocessForBadCharacterShift(pattern):map = { }for i in xrange(len(pattern)-1, -1, -1):c = pattern[i]if c not in map:map[c] = ireturn mapif __name__ == "__main__":matches = match("ana", "bananas")for integer in matches:print "Match at:", integerprint (matches == [1, 3] and "OK" or "Failed")matches = match([1, 2, 3], [0, 1, 2,3 , 4, 5, 6])for integer in matches:print "list Match at:", integerprint (matches)
https://en.xdnf.cn/q/72036.html

Related Q&A

How to initialise a 2D array in Python?

Ive been given the pseudo-code:for i= 1 to 3for j = 1 to 3board [i] [j] = 0next jnext iHow would I create this in python?(The idea is to create a 3 by 3 array with all of the elements set to 0 using a…

numpy: broadcast multiplication over one common axis of two 2d arrays

Im looking for a way to element-wise multiply two 2d arrays of shape (a, b) and (b, c), respectively. Over the b axis, which the two arrays have in common.For instance, an example of what Id like to br…

Convert integer to binary in python and compare the bits

How to convert a int n into binary and test each bit of the resulting binary number?I have just got the following after a lot of googling:def check_bit_positions(n, p1, p2):print int(str(n),2)However …

python, confused in decorate and closure

I have some test code:def num(num):def deco(func):def wrap(*args, **kwargs):inputed_num = numreturn func(*args, **kwargs)return wrapreturn deco@num(5) def test(a):return a + inputed_numprint test(1)whe…

Python Regex - checking for a capital letter with a lowercase after

I am trying to check for a capital letter that has a lowercase letter coming directly after it. The trick is that there is going to be a bunch of garbage capital letters and number coming directly befo…

Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy

I have a XML document that contains a hierarchical, tree-like structure, see the example below.The document contains several <Message> tags (I only copied one of them for convenience).Each <Me…

Reference counting using PyDict_SetItemString

Im wondering how memory management/reference counting works when a new value is set into an existing field within a PyDict (within a C extension).For instance, assume a dictionary is created and popula…

How to use statsmodels.tsa.seasonal.seasonal_decompose with a pandas dataframe

from statsmodels.tsa.seasonal import seasonal_decomposedef seasonal_decomp(df, model="additive"):seasonal_df = Noneseasonal_df = seasonal_decompose(df, model=additive)return seasonal_dfseason…

UnidentifiedImageError: cannot identify image file

Hello I am training a model with TensorFlow and Keras, and the dataset was downloaded from https://www.microsoft.com/en-us/download/confirmation.aspx?id=54765 This is a zip folder that I split in the …

Pydub raw audio data

Im using Pydub in Python 3.4 to try to detect the pitch of some audio files.I have a working pitch detection algorithm (McLeod Pitch Method), which is robust for real-time applications (I even made an …