Justify Frame Width in Python


Suppose we have a list of words, we have to frame it in a rectangular region, line by line. See the example for better understanding.

So, if the input is like ['hello','world', 'python', 'programming','nice'], then the output will be

***************
* hello       *
* world       *
* python      *
* programming *
* nice        *
***************

To solve this, we will follow these steps −

  • l:= length of maximum size word in the array
  • st:= put star (l+4) times
  • for each i in words, do
    • st := st concatenate '*' concatenate i then add space of size (l-size of i + 1) concatenate '*'
  • st:= concatenate star (l+4) times with st
  • return st

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, words):
      l=max(len(x) for x in words)
      st='*'*(l+4)+'\n'
      for i in words:
         st+='* '+i+' '*(l-len(i)+1)+'*'+'\n'
      return st+'*'*(l+4)
ob = Solution()
words = ['hello','world', 'python', 'programming','nice']
print(ob.solve(words))

Input

['hello','world', 'python', 'programming','nice']

Output

***************
* hello       *
* world       *
* python      *
* programming *
* nice        *
***************

Updated on: 23-Sep-2020

42 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements