Code Wars: Consecutive Strings Programming Problem

Jessica YungProgrammingLeave a Comment

Woe is me, I am a terrible programmer. Spoiler alert: Scroll down for terrible code followed by elegant code.


You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.

longest_consec([“zone”, “abigail”, “theta”, “form”, “libe”, “zas”, “theta”, “abigail”], 2) –> “abigailtheta”

n being the length of the string array, if n = 0 or k > n or k <= 0 return “”.


Debugging on CodeWars

My answer


And then I saw these three upvoted solutions:

Instead of storing the combinations in an array and then sorting them, this algorithm dynamically updates result as it goes through the array of strings.

The main reason my solution is so much uglier than these is because I translated the array of strings into an array of tuples with lengths and then did things with the translated list when that list didn’t have to be created in the first place. So don’t create unnecessary temp things.

This solution uses a list comprehension to store all combinations in a list and then takes the max. It takes the max length elegantly using a lambda function and the key attribute of max().

This final solution condenses code into one row. I’d argue it’s less readable, but hey one-row solutions are neat for competition purposes.

Leave a Reply