在 Python 中调整框架宽度
pythonserver side programmingprogramming更新于 2025/12/26 8:12:17
假设我们有一个单词列表,我们必须逐行将其框在一个矩形区域中。请参阅 示例以更好地理解。
因此,如果输入为 ['hello','world', 'python', 'programming','nice'],则输出将是
**************** * hello * * world * * python * * programming * * nice * ****************
为了解决这个问题,我们将遵循以下步骤 −
- l:= 数组中最大单词的长度
- st:= 放置 star (l+4) 次
- 对于 words 中的每个 i,执行
- st := st 连接 '*' 连接 i 然后添加大小为 (l-i + 1 的大小) 的空间连接 '*'
- st:= 将 star (l+4) 次与 st 连接
- 返回 st
让我们看看下面的实现以便更好地理解 −
示例
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))
输入
['hello','world', 'python', 'programming','nice']
输出
*************** * hello * * world * * python * * programming * * nice * ***************
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

