Split string by known substrings

Viewed 77

I've got a list of different strings (this is an example):

strs = ["FOOBAR", "PYTHON", "MAPARTS"]

and I've got another list with substrings that one of the strings in the previous list might contain:

substrs = ["ARTS", "FOO", "PY", "BAR", "MAP"]

I want to make a list that has all the strings in strs that can be split using two strings in substrs, split by them and wrapped in a list or tuple. So the finished list would look like:

[("FOO", "BAR"), ("MAP", "ARTS")]

I can't wrap my head around how to manage it, at least in a simple way. Any help?

3 Answers

Here is an interesting approach if you want to check if any combination of two tokens is a word listed in words:

from itertools import product

words = ["FOOBAR", "PYTHON", "MAPARTS"]

tokens = ["ARTS", "FOO", "PY", "BAR", "MAP"]

pairs = [_ for _ in product(tokens, tokens) if ''.join(_) in words]

Resulting in:

>>> pairs
[('FOO', 'BAR'), ('MAP', 'ARTS')]

The simplest approach would probably be to loop through the list of substrings. For each value in substrs, keep track (with your finished list) of whether prepending it to each of the other substrings results in a value that exists in strs.

finished = []
substrs = ["ARTS", "FOO", "PY", "BAR", "MAP"]
strs = ["FOOBAR", "PYTHON", "MAPARTS"]

for sub1 in substrs:
  for sub2 in substrs:
    combined = sub1 + sub2
    if combined in strs: finished.append((sub1, sub2))

There may be a more efficient algorithm, but this approach was the easiest way for me to solve the problem.

using itertools.permutations - >

import itertools
result = [
    item
    for item in itertools.permutations(substrs, 2)
    if ''.join(item) in strs
]

Here, the idea is to take all the permutation of length 2 and then join and check if that's available in 1st list or not

Related