-1

I have a list of characters:

groups = ['a', 'e', 'i', 'o', 'u']

And I have a list of words:

strings = ['testing', 'tested', 'fisherman', 'sandals', 'name']
  1. I need to split the words based on the characters mentioned in the groups list. The word "tested" can be grouped as "t + est + ed"

  2. Select the last group. So 'ed' in this case should be selected and only 'd' returned, because 'e' is already known.

expected={'testing':'ng', 'tested':'d', 'fisherman':'n', 'sandals':'ls', 'name':''}

If there is only 'e' then I can write:

'tested'.split('e')[-1]

But not sure how to check other characters.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
shantanuo
  • 31,689
  • 78
  • 245
  • 403

2 Answers2

1

Using regex:

import re    

groups = ['a', 'e', 'i', 'o', 'u']
strings = ['testing', 'tested', 'fisherman', 'sandals', 'name']

pat = "".join(groups)  # "aeiou"
expected = {s: re.search(f"[^{pat}]*$", s).group(0) for s in strings}
# {'testing': 'ng', 'tested': 'd', 'fisherman': 'n', 'sandals': 'ls', 'name': ''}
  • [^{pat}]*: zero or more (*) of not (^) any of pat
  • $: before the end of the word

If you want to implement this yourself:

def suffix(s, chars):
    for i in range(len(s)-1, -1, -1):
        if s[i] in chars:
            return s[i+1:]
    return s
 
>>> suffix("tested", "aeiou")
'd'
>>> suffix("testing", "aeiou")
'ng'
>>> suffix("name", "aeiou")
''
>>> {s: suffix(s, groups) for s in strings}
{'testing': 'ng', 'tested': 'd', 'fisherman': 'n', 'sandals': 'ls', 'name': ''}
user2390182
  • 72,016
  • 6
  • 67
  • 89
1
import re
groups = ['a', 'e', 'i', 'o', 'u']
pat = "|".join(groups)
strings = ['testing', 'tested', 'fisherman', 'sandals', 'name']
d = {s: re.split(pat, s)[-1] for s in strings}

This gives {'testing': 'ng', 'tested': 'd', 'fisherman': 'n', 'sandals': 'ls', 'name': ''}. Basically just following this