Domanda

Sto cercando una libreria Python per trovare la più lunga sottostringa comune da un insieme di stringhe . Ci sono due modi per risolvere questo problema:

  • utilizzando alberi di suffisso
  • usando la programmazione dinamica.

metodo implementato non è importante. E 'importante che può essere utilizzato per un insieme di stringhe (non solo due corde).

È stato utile?

Soluzione

Queste funzioni accoppiate troverà la stringa comune più lungo in qualsiasi array arbitrario di stringhe:

def long_substr(data):
    substr = ''
    if len(data) > 1 and len(data[0]) > 0:
        for i in range(len(data[0])):
            for j in range(len(data[0])-i+1):
                if j > len(substr) and is_substr(data[0][i:i+j], data):
                    substr = data[0][i:i+j]
    return substr

def is_substr(find, data):
    if len(data) < 1 and len(find) < 1:
        return False
    for i in range(len(data)):
        if find not in data[i]:
            return False
    return True


print long_substr(['Oh, hello, my friend.',
                   'I prefer Jelly Belly beans.',
                   'When hell freezes over!'])

Non c'è dubbio che l'algoritmo potrebbe essere migliorata e non ho avuto un sacco di esposizione a Python, quindi forse potrebbe essere più efficiente sintatticamente pure, ma dovrebbe fare il lavoro.

EDIT: in-allineato la seconda funzione is_substr come dimostrato da J.F. Sebastian. Uso rimane lo stesso. Nota:. Nessuna modifica all'algoritmo

def long_substr(data):
    substr = ''
    if len(data) > 1 and len(data[0]) > 0:
        for i in range(len(data[0])):
            for j in range(len(data[0])-i+1):
                if j > len(substr) and all(data[0][i:i+j] in x for x in data):
                    substr = data[0][i:i+j]
    return substr

Spero che questo aiuti,

Jason.

Altri suggerimenti

Io preferisco questo per is_substr, come mi trovo un po 'più leggibile e intuitiva:

def is_substr(find, data):
  """
  inputs a substring to find, returns True only 
  if found for each data in data list
  """

  if len(find) < 1 or len(data) < 1:
    return False # expected input DNE

  is_found = True # and-ing to False anywhere in data will return False
  for i in data:
    print "Looking for substring %s in %s..." % (find, i)
    is_found = is_found and find in i
  return is_found

Questo può essere fatto più breve:

def long_substr(data):
  substrs = lambda x: {x[i:i+j] for i in range(len(x)) for j in range(len(x) - i + 1)}
  s = substrs(data[0])
  for val in data[1:]:
    s.intersection_update(substrs(val))
  return max(s, key=len)

set di sono (probabilmente) implementato come hash-mappe, che rende questo un po 'inefficiente. Se (1) implementare un tipo di dati insieme come un trie e (2) solo memorizzare i suffissi nel trie e poi costringere ogni nodo per essere un endpoint (questo sarebbe l'equivalente di aggiungere tutte le sottostringhe), quindi, in teoria, direi questo bambino è abbastanza efficiente della memoria, soprattutto perché intersezioni di tentativi sono super-facile.

Tuttavia, questo è breve e l'ottimizzazione prematura è la radice di una notevole quantità di tempo sprecato.

def common_prefix(strings):
    """ Find the longest string that is a prefix of all the strings.
    """
    if not strings:
        return ''
    prefix = strings[0]
    for s in strings:
        if len(s) < len(prefix):
            prefix = prefix[:len(s)]
        if not prefix:
            return ''
        for i in range(len(prefix)):
            if prefix[i] != s[i]:
                prefix = prefix[:i]
                break
    return prefix

http://bitbucket.org/ned/cog/ src / tip / Cogapp / whiteutils.py

# this does not increase asymptotical complexity
# but can still waste more time than it saves. TODO: profile
def shortest_of(strings):
    return min(strings, key=len)

def long_substr(strings):
    substr = ""
    if not strings:
        return substr
    reference = shortest_of(strings) #strings[0]
    length = len(reference)
    #find a suitable slice i:j
    for i in xrange(length):
        #only consider strings long at least len(substr) + 1
        for j in xrange(i + len(substr) + 1, length + 1):
            candidate = reference[i:j]  # ↓ is the slice recalculated every time?
            if all(candidate in text for text in strings):
                substr = candidate
    return substr

responsabilità Questo aggiunge ben poco a risposta jtjacques'. Tuttavia, si spera, questo dovrebbe essere più leggibile e più veloce e che non rientrava in un commento, quindi, perché sto postando questo in una risposta. Non sono soddisfatto circa shortest_of, ad essere onesti.

Si potrebbe utilizzare il modulo albero dei suffissi che è un wrapper basata su un'implementazione ANSI C di alberi suffisso generalizzate. Il modulo è facile da gestire ....

Date un'occhiata a: qui

Se qualcuno è alla ricerca di una versione generalizzata che può anche prendere un elenco di sequenze di oggetti arbitrari:

def get_longest_common_subseq(data):
    substr = []
    if len(data) > 1 and len(data[0]) > 0:
        for i in range(len(data[0])):
            for j in range(len(data[0])-i+1):
                if j > len(substr) and is_subseq_of_any(data[0][i:i+j], data):
                    substr = data[0][i:i+j]
    return substr

def is_subseq_of_any(find, data):
    if len(data) < 1 and len(find) < 1:
        return False
    for i in range(len(data)):
        if not is_subseq(find, data[i]):
            return False
    return True

# Will also return True if possible_subseq == seq.
def is_subseq(possible_subseq, seq):
    if len(possible_subseq) > len(seq):
        return False
    def get_length_n_slices(n):
        for i in xrange(len(seq) + 1 - n):
            yield seq[i:i+n]
    for slyce in get_length_n_slices(len(possible_subseq)):
        if slyce == possible_subseq:
            return True
    return False

print get_longest_common_subseq([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])

print get_longest_common_subseq(['Oh, hello, my friend.',
                                     'I prefer Jelly Belly beans.',
                                     'When hell freezes over!'])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top