textwrap-library-solution-hackerrank

Hackerrank – Python – Text Wrap – Solution

Publish Date - February 17th, 2023

|

Last Modified - March 7th, 2023

Work smarter, not harder – is a good proverb to think by. While coding in Python, Java, C++, C# or any OOP web development language can seem daunting, what makes it so fundamentally sound is the fact that’s a language. This means you can solve a problem a million ways (and normally you want the easiest solution that’s the most reasonably sound). This solution can be overthought easily, but they literally give you the answer in the “Tutorial tab” at the beginning of the question. Anyways, hope this helps you in your Python journey:

Table of Contents

The problem

Check Tutorial tab to know how to to solve.

You are given a string  and width .
Your task is to wrap the string into a paragraph of width .

Function Description

Complete the wrap function in the editor below.

wrap has the following parameters:

  • string string: a long string
  • int max_width: the width to wrap to

Returns

  • string: a single string with newline characters (‘\n’) where the breaks should be

Input Format

The first line contains a string, .
The second line contains the width, .

Sample Input 0

ABCDEFGHIJKLIMNOQRSTUVWXYZ
4

Sample Output 0

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

The solution

import textwrap

def wrap(string, max_width):
    
    return textwrap.fill(string,max_width)

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

In the Hackerrank tutorial, they literally tell you how to use the function. The function has two inputs, just like the function “wrap” you’re creating, so why wouldn’t you just return both values VIA the textwrap.fill function?

While there are probably thousands of ways to find a solution, this is definitely the easiest.

I could see a solution where you loop through the entire string, and use conditionals to define the + / – of the max_width (so one increment down and one increment up) and then apply the textwrap..

However, that’d be over thinking it :). These types of solutions are regular in data science and machine learning due to their need for the code to be compact and engage with sometimes TBs of data to visualize.

Hope this answer helps you in your Python journey.

Leave a Comment

Your email address will not be published. Required fields are marked *