0
点赞
收藏
分享

微信扫一扫

笔面试编程题总结

天际孤狼 2024-08-08 阅读 29

文章目录

需求

给定一组字符串words和每行能显示的最大字符数max_length,计算需要多少行才能完整显示所有的单词。

分析

思路很简单,从给定的字符串中按空格分割单词列表,计算一行能显示的单词数,将其添加到list中

demo

def get_word_lines(words, max_length):
    lines = []
    line = ''
    word_list = words.split() # 按空格切分单词列表

    for word in word_list:
        if len(line) + len(word) <= max_length - 1: # 考虑空格
            line += (word + ' ')
        else:
            lines.append(line)
            line = word + ' '
    if line:
        lines.append(line)

    print('Require %d lines to show' % len(lines))
    # 打印单词列表,不足用-补齐
    for idx, wd in enumerate(lines):
        print(wd.ljust(max_length, '-'))
    return lines

测试用数据为:

words = 'In the above code, we first define an HTML text string, and then create a BeautifulSoup object using the BeautifulSoup library.'
print(get_word_lines(words, 20))

效果如下:
在这里插入图片描述

举报

相关推荐

0 条评论