Friday, 15 August 2014

string - Possible alignments of two lists using Python -



string - Possible alignments of two lists using Python -

i have 2 strings in 2 different lists a = [dog bit dog null] , b = [hund bet hund]. find possible allignments list b list such :

c = [(hund = dog, bet = bit, hund = dog), (hund = dog, bet = bit, hund = bit), (hund = dog, bet = bit, hund = null), (hund = dog, bet = dog, hund = dog), (hund = dog, bet = dog, hund = bit), etc.. ]

i think there 64 different allignments between these 2 strings. working on ibm model1 word translastion.

if want 64 possibilities, utilize itertools.product:

>>> itertools import product >>> = "dog bit dog null".split() >>> b = "hund bet hund".split() >>> product(a, repeat=3) <itertools.product object @ 0x1148fd500> >>> len(list(product(a, repeat=3))) 64 >>> list(product(a, repeat=3))[:5] [('dog', 'dog', 'dog'), ('dog', 'dog', 'bit'), ('dog', 'dog', 'dog'), ('dog', 'dog', 'null'), ('dog', 'bit', 'dog')]

but note going generate fair number of duplicates, given have dog twice in a:

>>> len(set(product(a, repeat=3))) 27

you associated triplets of pairs if wanted:

>>> trips = [zip(b, p) p in product(a, repeat=len(b))] >>> trips[:5] [[('hund', 'dog'), ('bet', 'dog'), ('hund', 'dog')], [('hund', 'dog'), ('bet', 'dog'), ('hund', 'bit')], [('hund', 'dog'), ('bet', 'dog'), ('hund', 'dog')], [('hund', 'dog'), ('bet', 'dog'), ('hund', 'null')], [('hund', 'dog'), ('bet', 'bit'), ('hund', 'dog')]]

python string list alignment

No comments:

Post a Comment