DEV Community

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

Posted on

4 3

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay