Print Words Vertically in PythonHow to print string vectors vertically in R?How to print the vector elements vertically in R?Python program to print even length words in a stringPrinting a list vertically in PythonJava program to print even length wordsSwift Program to Print even length wordsPrint all funny words in a string in C++C++ program to print unique words in a filePrint all possible words from phone digits in C++Print Words with Prime length from a SentenceHow to print number of words in textview in android?Print all words occurring in a sentence exactly K timesGiven a sequence of words, print all anagrams togetherUnique Morse Code Words in PythonPrint all words matching a pattern in CamelCase Notation Dictionary in C++ Print Words Vertically in Python

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: 2020-04-29T09:50:19+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started