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
OR
a d g
b e h
c f i
j
But not:
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[0].append('')
elif rows == 2:
grid[1].pop()
grid.append(['']*3)
elif extra_columns == 2:
if rows > 2:
grid[0].append('')
grid[1].append('')
else:
grid.append(['']*3)
assign_words(grid, words)
# special case
if 3 < word_count < 6:
print (grid[0][0]+ ' '+grid[0][2]+' '+grid[1][1])
print (grid[0][1]+ ' '+grid[1][0]+' '+grid[1][2])
return
# print grid
for col in range(len(grid[0])):
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'])
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'a', 'b', 'c', 'd']
be correctly printed as a 4 x 4 matrix? That's what I understand from: "as balanced as possible". If that's the case, your algorithm is wrong. \$\endgroup\$ – Grajdeanu Alex. Feb 26 '18 at 6:07