Printing words vertically in Python

| | | | | | | | | | | | | | | | | | | | | |

The given string s. Return all words vertically in the same order as they appear in s.
Words are returned as a string list, padded with spaces when necessary. (Walking on the steps is not allowed).
Each word will only be placed in one column and there will be only one word per column.

Printing words vertically in Python

Example 1:

Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically. 
 "HAY"
 "ORO"
 "WEU"

Example 2:

Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed. 
"TBONTB"
"OEROOE"
"   T"

Example 3:

Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]

Constraints:

  • 1 <= s.length <= 200
  • s contains only upper case English letters.
  • It’s guaranteed that there is only one space between 2 words.

Method #1 : [Horizontal to Vertical] using loop + ""

In this, we add newline character to after each character so that each element gets rendered at next line.

# Python3 code to demonstrate working of
# Interconvert Horizontal and Vertical String
# using [Horizontal to Vertical] using loop + "
"

# initializing string
test_str = ’geeksforgeeks’

# printing original String
print("The original string is : " + str(test_str))

# using loop to add "
" after each character
res = ’’
for ele in test_str:
	res += ele + "
"
	
# printing result
print("The converted string : " + str(res))

Output:

Output
The original string is : geeksforgeeks
The converted string : g
e
e
k
s
f
o
r
g
e
e
k
s

Method #2 : [Vertical to Horizontal] using replace() + ""

In this, we perform the task of conversion by removing "
" by replacement by empty string.

# Python3 code to demonstrate working of 
# Interconvert Horizontal and Vertical String
# using [Vertical to Horizontal] using replace() + "
"
  
# initializing string
test_str = ’g
e
e
k
s
f
o
r
g
e
e
k
s
’
  
# printing original String
print("The original string is : " + str(test_str))
  
# using replace() + "
" to solve this problem
res = test_str.replace("
", "")
      
# printing result 
print("The converted string : " + str(res)) 

Output:

The original string is : g
e
e
k
s
f
o
r
g
e
e
k
s

The converted string : geeksforgeeks
Printing words vertically in Python

Vertical Print String - Python3.2

StackOverflow question

I’m writing a script that will take as user inputed string, and print it vertically, like so:

input = "John walked to the store"

output = J w t t s
         o a o h t
         h l   e o
         n k     r
           e     e
           d

I’ve written most of the code, which is as follows:

import sys

def verticalPrint(astring):
    wordList = astring.split(" ")
    wordAmount = len(wordList)

    maxLen = 0
    for i in range (wordAmount):
        length = len(wordList[i])
        if length >= maxLen:
            maxLen = length

    ### makes all words the same length to avoid range errors ###
    for i in range (wordAmount):
        if len(wordList[i]) < maxLen:
            wordList[i] = wordList[i] + (" ")*(maxLen-len(wordList[i]))

    for i in range (wordAmount):
        for j in range (maxLen):
            print(wordList[i][j])

def main():
    astring = input("Enter a string:" + ’
’)

    verticalPrint(astring)

main()

I’m having trouble figure out how to get the output correct. I know its a problem with the for loop. It’s output is:

input = "John walked"

output = J
         o
         h
         n

         w
         a
         l
         k
         e
         d

Any advice? (Also, I want to have the print command used only once.)

Answer:

Use itertools.zip_longest:

>>> from itertools import zip_longest
>>> text = "John walked to the store"
for x in zip_longest(*text.split(), fillvalue=’ ’):
    print (’ ’.join(x))
...     
J w t t s
o a o h t
h l   e o
n k     r
  e     e
  d      

Suppose we have string s. We have to find all the words vertically in the same order in which they appear in s. Here the words are returned as a list of strings, if necessary, we have to fill in spaces. (Trailing spaces are not allowed.) Each word will be placed in only one column, and there will be only one word in one column. Thus, if the input string is "LIKE YOU?", Then the output will be ["HAY", "ORO", "WEU"]

To solve this problem, we will follow the following 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
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"]
Printing words vertically in Python