Created
August 3, 2022 14:53
-
-
Save Einenlum/908eaca08b2dd31b4586a9cc76ceb79d to your computer and use it in GitHub Desktop.
A python function to take a list of words and print them in two columns side by side
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I needed a way to print two columns of words based on a list and a number of spaces. | |
# I couldn't find an easy solution, so I made this function. Maybe it can be useful to someone. | |
from typing import List | |
def outputs(words: List[str], spaces: int) -> str: | |
""" | |
Takes a list of words and returns two columns of words separated by spaces. | |
Example: outputs([ | |
"mess", | |
"lot", | |
"address", | |
"pardon", | |
"selection", | |
"estate", | |
"meet", | |
"deprive", | |
"fairy", | |
"bread", | |
"book", | |
"hurt", | |
"area" | |
], 4) | |
Returns the following string: | |
mess meet | |
lot deprive | |
address fairy | |
pardon bread | |
selection book | |
estate hurt | |
area | |
""" | |
def _get_spaces_number(max_length: int, word: str) -> int: | |
return max_length + spaces - len(word) | |
max_length = max(map(len, words)) | |
num_words = len(words) | |
half = num_words // 2 | |
num_rest = num_words % 2 | |
left = words[:half] | |
right = words[half : len(words) - num_rest] | |
rest = words[len(words) - num_rest :] | |
output = "" | |
for left_word, right_word in zip(left, right): | |
output += ( | |
left_word | |
+ " " * _get_spaces_number(max_length, left_word) | |
+ right_word | |
+ "\n" | |
) | |
for word in rest: | |
output += word + "\n" | |
return output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment