# Number of Lines To Write String in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string S and we have to write the letters of that given string, from left to right into lines. Here each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, that will be written on the next line. We also have an array widths, here widths is the width of 'a', widths is the width of 'b'and so on.

We have to find the answers of two questions −

• How many lines have at least one character from S
• What is the width used by the last such line?

We will return the answer as an integer list of length 2.

So, if the input is like [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] and S = "bbbcccdddaaa", then the output will be [2, 4], as all letters except 'a' have the same length of 10, and the string "bbbcccdddaa" will cover 9 * 10 + 2 * 4 = 98 spaces. For the last 'a', it is written on the second line because there is only 2 units left in the first line. So the answer is 2 lines, plus 4 units in the second line.

To solve this, we will follow these steps −

• line := 1, count := 0
• for each i in S, do
• count := count + widths[ASCII of i - 97]
• if count > 100, then
• line := line + 1
• count := widths[ASCII of i - 97]
• return [line, count]

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def numberOfLines(self, widths, S):
line = 1
count = 0
for i in S:
count += widths[ord(str(i))-97]
if count > 100:
line += 1
count = widths[ord(str(i))-97]
return [line, count]
ob = Solution()
print(ob.numberOfLines([4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], "bbbcccdddaaa"))

## Input

[4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],"bbbcccdddaaa"

## Output

[2, 4]