HackerRank Solution: Python Text Alignment [2 Methods]


Hacker Rank Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Question: Text Alignment [Python Strings]

In Python, a string of text can be aligned left, right and center.

.ljust(width)

This method returns a left-aligned string of length width.

>>> width = 20
>>> print 'HackerRank'.ljust(width,'-')
HackerRank----------  

.center(width)

This method returns a centered string of length width.

>>> width = 20
>>> print 'HackerRank'.center(width,'-')
-----HackerRank-----

.rjust(width)

This method returns a right-aligned string of length width.

>>> width = 20
>>> print 'HackerRank'.rjust(width,'-')
----------HackerRank

Task

You are given a partial code that is used for generating the HackerRank Logo of variable thickness.
Your task is to replace the blank (______) with rjust, ljust or center.

Input Format

A single line containing the thickness value for the logo.

Constraints

The thickness must be an odd number.

0 < thickness < 50

Output Format

Output the desired logo.

Sample Input

5

Sample Output

    H    
   HHH   
  HHHHH  
 HHHHHHH 
HHHHHHHHH
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHHHHHHHHHHHHHHHHHHHHHH   
  HHHHHHHHHHHHHHHHHHHHHHHHH   
  HHHHHHHHHHHHHHHHHHHHHHHHH   
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHH               HHHHH             
  HHHHH               HHHHH             
                    HHHHHHHHH 
                     HHHHHHH  
                      HHHHH   
                       HHH    
                        H

 

Possible Solutions

Now let us move toward the possible solutions for the given problem. The following code is already given in the editor of the Hacker Rank:

#Replace all ______ with rjust, ljust or center. 

thickness = int(input()) #This must be an odd number
c = 'H'

#Top Cone
for i in range(thickness):
    print((c*i).______(thickness-1)+c+(c*i).______(thickness-1))

#Top Pillars
for i in range(thickness+1):
    print((c*thickness).______(thickness*2)+(c*thickness).______(thickness*6))

#Middle Belt
for i in range((thickness+1)//2):
    print((c*thickness*5).______(thickness*6))    

#Bottom Pillars
for i in range(thickness+1):
    print((c*thickness).______(thickness*2)+(c*thickness).______(thickness*6))    

#Bottom Cone
for i in range(thickness):
    print(((c*(thickness-i-1)).______(thickness)+c+(c*(thickness-i-1)).______(thickness)).______(thickness*6))

Now, let us move toward the solutions.

 

Solution-1: Using a user-defined function

We will now use a user-defined function in order to solve the problem.

t = int(input()) # thickness
assert t % 2 == 1
total_width = t * 6
ch = 'H'         # filler

def cone(aligned_left: bool = False, pointing_down: bool = False):
    width = t * 2 - 1
    layer_gen = range(t)
    align = '>' if aligned_left else '<'
    if pointing_down:
        layer_gen = reversed(layer_gen)
        
    for layer in layer_gen:
        unaligned_layer = f"{ch * (1 + layer * 2): ^{width}}"
        print(f"{unaligned_layer:{align}{total_width - 1}}")

def pillars():
    for layer in range(t + 1):
        print(f"{ch * t: ^{t*2}}{ch * t:^{total_width}}")
        
def middle_belt():
    for i in range((t + 1) // 2):
        print(f"{ch * t * 5: ^{total_width}}")

cone()                                      #Top Cone
pillars()                                   #Top Pillars
middle_belt()                               #Middle Belt
pillars()                                   #Bottom Pillars
cone(aligned_left=True, pointing_down=True) #Bottom Cone

This code generates the ASCII art of a cylinder. The thickness "t" of the cylinder is taken as input and must be an odd number. The total width of the cylinder is calculated as 6 times the thickness. The filler character "H" is defined. The "cone" function generates the top and bottom cones of the cylinder by printing layers of characters with increasing/decreasing width, and can be aligned to either side and pointed either up or down. The "pillars" function generates the top and bottom belts of the cylinder by printing layers of characters with the same width as the thickness. The "middle_belt" function generates the middle belt of the cylinder by printing lines of characters with the same width as 5 times the thickness. All of these functions use the "print" statement and string formatting to generate the ASCII art output.

 

Solution-2: Using for loop

We can use the for loop to solve the problem.

thickness = int(input()) #This must be an odd number
c = 'H'

#Top Cone
for i in range(thickness):
    print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1))

#Top Pillars
for i in range(thickness+1):
    print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))

#Middle Belt
for i in range((thickness+1)//2):
    print((c*thickness*5).center(thickness*6))    

#Bottom Pillars
for i in range(thickness+1):
    print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))    

#Bottom Cone
for i in range(thickness):
    print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6))

Similar to the previous solution, this solution also generates the ASCII art of a cylinder. The user inputs the thickness "thickness" of the cylinder, which must be an odd number. The filler character "c" is defined as "H". The code then generates the top cone of the cylinder by printing layers of characters with increasing width using the "print" statement and the "rjust" and "ljust" string methods. The top pillars of the cylinder are generated by printing lines of characters with the same width as the thickness and centered using the "center" string method. The middle belt of the cylinder is generated by printing lines of characters with the same width as 5 times the thickness and centered. The bottom pillars of the cylinder are generated in the same way as the top pillars. Finally, the bottom cone of the cylinder is generated by printing layers of characters with decreasing width and right-justified using the "rjust" method

 

Summary

In this short article, we discussed how we can solve the text alignment problem on hacker rank. We covered two solutions and explained each of them.

 

Further Reading

Question on the hacker rank: Python Text Alignment [Strings]

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment