Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print Words Vertically in Python
Printing words vertically means taking each character at the same position from different words and forming new strings. For example, if we have "HOW ARE YOU", we take the first character from each word (H, A, Y) to form "HAY", second characters (O, R, O) to form "ORO", and so on.
Algorithm Steps
To solve this problem, we follow these steps ?
Split the input string into words
Find the maximum length among all words (this determines how many vertical strings we need)
For each position, collect characters from all words at that position
Add spaces when a word is shorter than the current position
Remove trailing spaces from each result string
Example
Let us see the implementation to understand better ?
class Solution:
def printVertically(self, s):
words = s.split(" ")
max_length = max(len(word) for word in words)
result = []
# For each character position
for i in range(max_length):
vertical_word = ""
# Collect character from each word at position i
for word in words:
if i < len(word):
vertical_word += word[i]
else:
vertical_word += " "
# Remove trailing spaces
result.append(vertical_word.rstrip())
return result
# Test the solution
solution = Solution()
print(solution.printVertically("HOW ARE YOU"))
print(solution.printVertically("TO BE OR NOT TO BE"))
The output of the above code is ?
['HAY', 'ORO', 'WEU'] ['TBONTB', 'OEROOE', ' T']
How It Works
Let's trace through "HOW ARE YOU" ?
Words: ["HOW", "ARE", "YOU"]
Maximum length: 3
Position 0: H (from HOW) + A (from ARE) + Y (from YOU) = "HAY"
Position 1: O (from HOW) + R (from ARE) + O (from YOU) = "ORO"
Position 2: W (from HOW) + E (from ARE) + U (from YOU) = "WEU"
Alternative Approach Using zip_longest
We can use Python's itertools.zip_longest for a more concise solution ?
from itertools import zip_longest
def print_vertically(s):
words = s.split()
# Transpose words using zip_longest
vertical_words = []
for chars in zip_longest(*words, fillvalue=' '):
vertical_word = ''.join(chars).rstrip()
vertical_words.append(vertical_word)
return vertical_words
# Test the function
print(print_vertically("HOW ARE YOU"))
print(print_vertically("TO BE OR NOT TO BE"))
The output of the above code is ?
['HAY', 'ORO', 'WEU'] ['TBONTB', 'OEROOE', ' T']
Conclusion
Printing words vertically involves transposing character positions across words. The key is finding the maximum word length and handling shorter words with spaces, while removing trailing spaces from the result.
