Print Words Vertically in Python

Suppose we have a string s. We have to find all the words vertically in the same order in which they appear in s. Here words are returned as a list of strings, we have to complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. So if the input string is “HOW ARE YOU”, then the output will be [“HAY”, “ORO”, “WEU”]

To solve this, we will follow these steps −

• s := make a list of strings split by the spaces, make one empty array x, set row = 0

• for each word I in s, set row := max of row and length of i

• col := length of s

• make one array and filled with empty string, and its size is the row

• for I in range 0 to col – 1

• j := 0

• while j < length of s[i]

• while i – length of ans[j] >= 1, do ans[j] := ans[j] concatenate “ ”

• ans[j] := ans[j] concatenate s[i, j]

• increase j by 1

• return ans

Example (Python)

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def printVertically(self, s):
s = s.split(" ")
x = []
row = 0
for i in s:
row = max(row, len(i))
col = len(s)
ans = ["" for i in range(row)]
j = 0
for i in range(col):
j = 0
while j < len(s[i]):
#print(j, i)
while i - len(ans[j]) >= 1:
ans[j] += " "
ans[j] += s[i][j]
j += 1
return ans
ob = Solution()
print(ob.printVertically("HOW ARE YOU"))
print(ob.printVertically("TO BE OR NOT TO BE"))

Input

"HOW ARE YOU"
"TO BE OR NOT TO BE"

Output

["HAY","ORO","WEU"]
["TBONTB","OEROOE"," T"]

Updated on: 29-Apr-2020

3K+ Views