在 Python 中调整框架宽度


假设我们有一个单词列表,我们需要将其逐行框在一个矩形区域中。请参阅示例以加深理解。

所以,如果输入类似于 ['hello','world', 'python', 'programming','nice'],那么输出将是

***************
* hello       *
* world       *
* python      *
* programming *
* nice        *
***************

为了解决这个问题,我们将遵循以下步骤 −

  • l:= 数组中最大长度单词的长度
  • st:= 星号 (l+4) 倍
  • 对单词中的每个 i 执行以下操作
    • st := st 连接 '*' 连接 i 然后添加大小为 (l-i 大小 + 1) 的空格连接 '*'
  • st:= 星号 (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        *
***************

更新于: 23-Sep-2020

56 次浏览

启动你的 职业

通过完成此课程获得认证

开始
广告
© . All rights reserved.