Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Justify Frame Width in Python
When we have a list of words, we can frame them in a rectangular region with stars and proper spacing. This creates a visual frame around the text, line by line.
Problem Understanding
Given a list of words, we need to create a rectangular frame where each word is on its own line, padded with spaces to maintain uniform width, and surrounded by asterisks.
For example, if the input is ['hello', 'world', 'python', 'programming', 'nice'], the output will be ?
*************** * hello * * world * * python * * programming * * nice * ***************
Algorithm Steps
To solve this problem, we follow these steps ?
- Find the length of the longest word in the list
- Create the top border using stars (longest_length + 4 times)
- For each word, create a line with proper padding
- Add the bottom border using the same number of stars
Implementation
class Solution:
def solve(self, words):
# Find the length of the longest word
max_length = max(len(word) for word in words)
# Create top border
border = '*' * (max_length + 4)
result = border + '\n'
# Add each word with proper spacing
for word in words:
spaces_needed = max_length - len(word) + 1
line = '* ' + word + ' ' * spaces_needed + '*\n'
result += line
# Add bottom border
result += border
return result
# Test the solution
solution = Solution()
words = ['hello', 'world', 'python', 'programming', 'nice']
print(solution.solve(words))
*************** * hello * * world * * python * * programming * * nice * ***************
How It Works
The algorithm calculates the frame width based on the longest word. Each line follows the pattern: * word spaces * where the number of spaces ensures all lines have the same total width.
Alternative Implementation
Here's a more concise version using list comprehension ?
def justify_frame(words):
max_len = max(len(word) for word in words)
border = '*' * (max_len + 4)
lines = [border]
lines.extend(f"* {word}{' ' * (max_len - len(word) + 1)}*" for word in words)
lines.append(border)
return '\n'.join(lines)
# Test the function
words = ['hello', 'world', 'python', 'programming', 'nice']
print(justify_frame(words))
*************** * hello * * world * * python * * programming * * nice * ***************
Conclusion
This solution creates a justified frame by calculating the maximum word length and padding each line accordingly. The frame width is determined by the longest word plus 4 characters for borders and spacing.
