Il modo migliore per determinare se una sequenza si trova in un'altra sequenza in Python

StackOverflow https://stackoverflow.com/questions/425604

  •  06-07-2019
  •  | 
  •  

Domanda

Questa è una generalizzazione della stringa " contiene sottostringa " problema a (più) tipi arbitrari.

Data una sequenza (come un elenco o una tupla), qual è il modo migliore per determinare se al suo interno è presente un'altra sequenza? Come bonus, dovrebbe restituire l'indice dell'elemento in cui inizia la sottosequenza:

Esempio di utilizzo (sequenza in sequenza):

>>> seq_in_seq([5,6],  [4,'a',3,5,6])
3
>>> seq_in_seq([5,7],  [4,'a',3,5,6])
-1 # or None, or whatever

Finora mi baso solo sulla forza bruta e sembra lento, brutto e goffo.

È stato utile?

Soluzione

Secondo, l'algoritmo Knuth-Morris-Pratt. A proposito, il tuo problema (e la soluzione KMP) è esattamente la ricetta 5.13 in Cookbook Python 2a edizione. È possibile trovare il codice correlato su http://code.activestate.com/recipes/117214/

Trova tutto le sottosequenze corrette in una data sequenza e dovrebbe essere usato come iteratore:

>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,6]): print s
3
>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,7]): print s
(nothing)

Altri suggerimenti

Ecco un approccio a forza bruta O (n * m) (simile a La risposta di @mcella ). Potrebbe essere più veloce dell'implementazione dell'algoritmo Knuth-Morris-Pratt in Python O (n + m) puro (vedi @ Risposta di Gregg Lind ) per piccole sequenze di input.

#!/usr/bin/env python
def index(subseq, seq):
    """Return an index of `subseq`uence in the `seq`uence.

    Or `-1` if `subseq` is not a subsequence of the `seq`.

    The time complexity of the algorithm is O(n*m), where

        n, m = len(seq), len(subseq)

    >>> index([1,2], range(5))
    1
    >>> index(range(1, 6), range(5))
    -1
    >>> index(range(5), range(5))
    0
    >>> index([1,2], [0, 1, 0, 1, 2])
    3
    """
    i, n, m = -1, len(seq), len(subseq)
    try:
        while True:
            i = seq.index(subseq[0], i + 1, n - m + 1)
            if subseq == seq[i:i + m]:
               return i
    except ValueError:
        return -1

if __name__ == '__main__':
    import doctest; doctest.testmod()

Mi chiedo quanto è grande il piccolo in questo caso?

Stessa cosa per la corrispondenza delle stringhe signore ... Knuth-Morris-Pratt stringa corrispondente

Un approccio semplice: converti in stringhe e fai affidamento sulla corrispondenza delle stringhe.

Esempio usando liste di stringhe:

 >>> f = ["foo", "bar", "baz"]
 >>> g = ["foo", "bar"]
 >>> ff = str(f).strip("[]")
 >>> gg = str(g).strip("[]")
 >>> gg in ff
 True

Esempio usando tuple di stringhe:

>>> x = ("foo", "bar", "baz")
>>> y = ("bar", "baz")
>>> xx = str(x).strip("()")
>>> yy = str(y).strip("()")
>>> yy in xx
True

Esempio usando liste di numeri:

>>> f = [1 , 2, 3, 4, 5, 6, 7]
>>> g = [4, 5, 6]
>>> ff = str(f).strip("[]")
>>> gg = str(g).strip("[]")
>>> gg in ff
True
>>> def seq_in_seq(subseq, seq):
...     while subseq[0] in seq:
...         index = seq.index(subseq[0])
...         if subseq == seq[index:index + len(subseq)]:
...             return index
...         else:
...             seq = seq[index + 1:]
...     else:
...         return -1
... 
>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1

Mi dispiace non sono un esperto di algoritmi, è solo la cosa più veloce a cui la mia mente può pensare al momento, almeno penso che sia carino (per me) e mi sono divertito a programmarlo. ; -)

Molto probabilmente è la stessa cosa che sta facendo il tuo approccio alla forza bruta.

La forza bruta può andare bene per piccoli schemi.

Per quelli più grandi, guarda Algoritmo Aho-Corasick .

Ecco un'altra implementazione di KMP:

from itertools import tee

def seq_in_seq(seq1,seq2):
    '''
    Return the index where seq1 appears in seq2, or -1 if 
    seq1 is not in seq2, using the Knuth-Morris-Pratt algorithm

    based heavily on code by Neale Pickett <neale@woozle.org>
    found at:  woozle.org/~neale/src/python/kmp.py

    >>> seq_in_seq(range(3),range(5))
    0
    >>> seq_in_seq(range(3)[-1:],range(5))
    2
    >>>seq_in_seq(range(6),range(5))
    -1
    '''
    def compute_prefix_function(p):
        m = len(p)
        pi = [0] * m
        k = 0
        for q in xrange(1, m):
            while k > 0 and p[k] != p[q]:
                k = pi[k - 1]
            if p[k] == p[q]:
                k = k + 1
            pi[q] = k
        return pi

    t,p = list(tee(seq2)[0]), list(tee(seq1)[0])
    m,n = len(p),len(t)
    pi = compute_prefix_function(p)
    q = 0
    for i in range(n):
        while q > 0 and p[q] != t[i]:
            q = pi[q - 1]
        if p[q] == t[i]:
            q = q + 1
        if q == m:
            return i - m + 1
    return -1

Sono un po 'in ritardo alla festa, ma ecco qualcosa di semplice usando le stringhe:

>>> def seq_in_seq(sub, full):
...     f = ''.join([repr(d) for d in full]).replace("'", "")
...     s = ''.join([repr(d) for d in sub]).replace("'", "")
...     #return f.find(s) #<-- not reliable for finding indices in all cases
...     return s in f
...
>>> seq_in_seq([5,6], [4,'a',3,5,6])
True
>>> seq_in_seq([5,7], [4,'a',3,5,6])
False
>>> seq_in_seq([4,'abc',33], [4,'abc',33,5,6])
True


Come notato da Ilya V. Schurov , il metodo trova in questo caso non restituirà gli indici corretti con stringhe a più caratteri o numeri a più cifre.

Un altro approccio, usando set:

set([5,6])== set([5,6])&set([4,'a',3,5,6])
True
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top