Pages

CodeEval Stepwise Word

Write a function that, given in input a list of words, gives back the longest one, in a stepwise fashion. This is the 202 CodeEval problem. Here I am going to show my Python 3 solution.

Firstly, I have converted their example in unit tests. Having a look at them should be clear what they mean for "stepwise".
def test_provided_1(self):
    result = solution('cat dog hello')
    self.assertEqual('h *e **l ***l ****o', result)

def test_provided_2(self):
    result = solution('stop football play')
    self.assertEqual('f *o **o ***t ****b *****a ******l *******l', result)

def test_provided_3(self):
    result = solution('music is my life')
    self.assertEqual('m *u **s ***i ****c', result)
Then, I have divided the problem in two parts. Finding the longest word, and then converting a word in the weird format required.

The longest word could be found in linear time. It is just a matter of keeping track of the currently found solution, comparing its size against the other candidates until a better solution is found or we reach the end of the list:
def get_longest_word(line):
    words = line.split()
    selected = ''
    for word in words:
        if len(word) > len(selected):
            selected = word
    return selected
I get the "stepwise" format by concatenating a growing number of stars followed by the actual character for each step, and then pushing the result in a temporary list. Finally, I join the list on a blank to get the expected string:
result = []
for i in range(len(word)):
    result.append('*' * i + word[i])
return ' '.join(result)
I submitted successfully my solution to CodeEval, and then I have pushed to GitHub both the unit test and the python3 source file.

No comments:

Post a Comment