DEV Community

Cover image for Python Word Split Algorithm, Coderbyte
Ugwu Arinze Christopher
Ugwu Arinze Christopher

Posted on

Python Word Split Algorithm, Coderbyte

Problem Definition:

Have the function WordSplit(strArr) read the array of strings stored in strArr, which will contain 2 elements: the first element will be a sequence of characters, and the second element will be a long string of comma-seperated words, in alphabetical order, that represents a dictionary of some arbitrary length. For example: strArr can be:
["hellocat", "apple, bat, cat, goodbye, hello, yellow, why"].
Your goal is to determine if the first element in the input can be split into two words, where both words in the dictionary that is provided in the second input.
In this example, the firs element can be split into two words:
hello and cat because both of those words are in the dictionary.

Your program should return the two words that exist in the dictionary separated by a comma. So for the example above, your program should return hello, cat. There will only be one correct way to split the first element of characters into two words. If there is no way to split string into two words that exist in the dictionary, return the string not possible. The first element itself will never exist in the dictionary as a real word.

# define the function to manipulate string

def WordSplit(strArr):
  for i, j in enumerate(strArr[1].split(',')):
    '''subtract a string from the main string'''

    new = strArr[0].replace(j.strip(),'')  

    '''then search through the other strings and compare with the remainder after subtraction'''

    for x in strArr[1].split(','):
      if new == x.strip():
        if strArr[0] == j.strip() + new:
          return f'{j.strip()},{new}'

  return 'not possible'

strArr = ['baseball', 'a, all, b, ball,base,  bas,  cat, code, d, e, quit, z'] #test case

response = WordSplit(strArr)    
'''intersperse this code with the ouput of the function'''
code = 'fg23klq6r9'

print(response )
intersperse = ''.join(i+j for i, j in zip(response, code))
print(intersperse )
Enter fullscreen mode Exit fullscreen mode

Top comments (0)