The challenge

What if we need the length of the words separated by a space to be added at the end of that same word and have it returned as an array?

1
2
add_length('apple ban') => ["apple 5", "ban 3"]
add_length('you will win') => ["you 3", "will 4", "win 3"]

Your task is to write a function that takes a String and returns an Array/list with the length of each word added to each element.

Note: String will have at least one element; words will always be separated by a space.

The solution in Python code

Option 1:

1
2
def add_length(str_):
    return [str(x)+' '+str(len(x)) for x in str_.split(' ')]

Option 2:

1
2
def add_length(string):
    return ["{} {}".format(word, len(word)) for word in string.split(" ")]

Option 3:

1
2
3
4
5
def add_length(str_):
    answer = []
    for word in str_.split():
        answer.append(word + ' ' + str(len(word)))
    return answer

Test cases to validate our solution

1
2
3
4
5
6
7
8
9
import test
from solution import add_length

@test.describe("Fixed Tests")
def basic_tests():
    test.assert_equals(add_length('apple ban'),["apple 5", "ban 3"])
    test.assert_equals(add_length('you will win'),["you 3", "will 4", "win 3"])
    test.assert_equals(add_length('you'),["you 3"])
    test.assert_equals(add_length('y'),["y 1"])