Simple, get every n
th word in a string.
Trying to optimize it. Words are split by a single space " ".
Does not start with the first word.
decode("Hello World", 2) -> "World"
decode("1 2 3 4 5 6 7 8 9", 3) -> "3 6 9"
decode("Lorem ipsum dolor sit amet", 1) -> "Lorem ipsum dolor sit amet"
decode("There aren't enough words.", 5) -> ""
def get_nth_words(string, n):
if n < 1: return ""
return ' '.join(['',*string.split()][::n][1:])
import codewars_test as test
from solution import get_nth_words
basictests = [
["Hello World", 2, "World"],
["1 2 3 4 5 6 7 8 9", 3, "3 6 9"],
["Lorem ipsum dolor sit amet", 1, "Lorem ipsum dolor sit amet"],
["And a one and a two and a three and a four", 3, "one two three four"]
]
notenoughwords = [
["There aren't enough words.", 5, ""],
["What if there weren't enough words?", 15, ""],
["What are the chances of there being enough words?", 150, ""],
["", 5000, ""]
]
attempterrors = [
["", 1, ""],
["error 1 2 3 4", 0, ""],
["Hmm... What about this?", -1, ""],
["", -5, ""]
]
@test.describe("Basic Tests")
def basic_test_group():
@test.it("Basic Tests")
def basic_tests():
for tst in basictests:
test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])
@test.it("Not Enough Words")
def not_enough_words():
for tst in notenoughwords:
test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])
@test.it("Exception Handling")
def cause_errors():
for tst in attempterrors:
test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])