I recently gave a test on HackerRank:
Given a string, return the most concise string that can be formed from it.
For example:
string = 'watson Represents|watson represents|Watson represents a first step into cognitive systems, a new era of computing.|first step into Cognitive|Cognitive Systems; a new era|what does watson represent'
- The following string contains many duplicates like "Watson represents." We have to ignore extra spacing between characters or lower/upper case. "watson Represents" and "watson represents" are the same thing.
- Semicolons and commas represent the same thing. For example, "Cognitive Systems; a new era" is present inside "Watson represents a first step into cognitive systems, a new era of computing."
- Your final string should not contain any duplicates. Ignore lowercase/uppercase or extra space if you have any.
My answer:
watson = 'watson Represents|watson represents|Watson represents a first step into cognitive systems, a new era of computing.|first step into Cognitive|Cognitive Systems; a new era|what does watson represent'
import re
watson = re.sub(r';', r',', watson) #replace the semicolon with colon
watson = watson.strip().split('|')
removeWatson = list(watson)
for i in range(len(watson)):
for j in range(len(watson)):
if j == i:
continue
if " ".join(watson[i].strip().lower().split()) in " ".join(watson[j].strip().lower().split()):
removeWatson[i] = ''
print "|".join(filter(None, removeWatson))
My answer is definitely inefficient and I am wondering if you can suggest an alternative way of solving this problem.
Most concise string:
Watson represents a first step into cognitive systems, a new era of computing.|what does watson represent