This was a interview question I struggled with, I am posting my solution hoping to look for more elegant/efficient solutions.
Problem: Given a list of strings, print its element out to STDOUT one by one vertically into 3 columns, while making sure the 3 columns' length are as balanced as possible.
For example, given list = ['a','b','c','d','e','f','g','h','i','j']
The output could be either:
a e h b f i c g j d
a d g b e h c f i j
a e i b f j c g d h
My approach in Python 3:
Basically I put each word into a "N by 3" 2D list horizontally and try to print them out vertically. If the length is not divisible by 3, I manually increase the length of the first 2 rows depending on the remainder. This creates quite a few edge cases for me to handle separately, such as when the length of the list is between 3 and 6 or when the length is less than or equal to 3.
def assign_words(grid, words): i = 0 for row in range(len(grid)): for col in range(len(grid[row])): grid[row][col] = words[i] i += 1 if i == len(words): return def print_words(words): word_count = len(words) rows = word_count // 3 extra_columns = word_count % 3 grid = [[''] * 3 for _ in range(rows)] # special case if word_count <= 3: grid.append(['']*3) assign_words(grid, words) for row in grid: print (' '.join(row)) return if extra_columns == 1: if rows > 2: grid.append('') elif rows == 2: grid.pop() grid.append(['']*3) elif extra_columns == 2: if rows > 2: grid.append('') grid.append('') else: grid.append(['']*3) assign_words(grid, words) # special case if 3 < word_count < 6: print (grid+ ' '+grid+' '+grid) print (grid+ ' '+grid+' '+grid) return # print grid for col in range(len(grid)): for row in range(len(grid)): if col == len(grid[row]): break print (grid[row][col], end=' ') print () print_words(['a','b','c','d','e','f','g'])