Member-only story
Here is an interesting problem I came across recently: Consider a list of lines consisting of a single number followed by a single (lower case) word. Now, sort these lines by the initial number and filter out all lines whose line index is not in the sequence (i)(i + 1)/2 for some integer, i. Then, create a joined string of the word values of said lines. How would you approach this problem in both Python and Elixir?
First, let’s try to code up a version in Python. We might start by splitting the text by lines, filtering out empty lines, converting the numbers to ints, then sorting the resultant array by the first element (the number):
lines = word_text.split("\n")
nums_and_words = [line.split() for line in lines]
nums_and_words = filter(lambda line: line, nums_and_words)
nums_and_words = [[int(num), word] for num, word in nums_and_words]
nums_and_words = sorted(nums_and_words, key=lambda lst: lst[0])Then, we start out i at 1 and the referent index at 0, iterate over the array, and add the appropriate lines to our to-be-generated array:
i = 1
cur = 0
words = []
while cur < len(nums_and_words):
words.append(nums_and_words[cur])
i += 1
cur = (i * (i + 1) // 2) - 1Finally, we join the words together:
words = " ".join(word for num, word in words)