|
66鱼币
本帖最后由 x287208793 于 2019-10-10 17:03 编辑
如题,上半部分,被我折腾出来了,后面排序,填充空格,试了好久都没写出来,来个大佬指点下
每日一题第253题
以下是我折腾的部分代码:
- def the_words(words,maxwidth):
- new_words = []
- while words:
- sum = 0
- for each in words: #遍历words列表中的每个元素
- sum += len(each) +1 #获取每个元素的累加后的字符长度,每个字符加上一个空格['this is an ']
- if sum > maxwidth: #如果遍历累加后的长度大于分割长度maxwidth
- new_words.append(' '.join(words[0:words.index(each)]))
- words = words[words.index(each):]
- break
- elif sum == maxwidth:
- new_words.append(' '.join(words[0:(words.index(each) + 1)]))
- words = words[(words.index(each) + 1):]
- break
- elif sum < maxwidth and len(' '.join(words) ) < maxwidth:
- new_words.append(' '.join(words))
- words = []
- break
- print(new_words)
- words = ["This", "is", "an", "example", "of", "text", "justification."]
- maxwidth = 16
- the_words(words,maxwidth)
复制代码
- def kao(lst, maxwidth):
- result = []
- for w in lst:
- spaces = maxwidth - len(w)
- lt = w.split()
- slen = len(lt)
- if slen == 1:
- lt[0] = lt[0] + '龢' * spaces
- if slen > 1:
- a, b = divmod(spaces, slen - 1)
- if a > 0:
- for ele in range(slen - 1):
- lt[ele] = lt[ele] + '龢' * a
- if b > 0:
- for ele in range(0, b):
- lt[ele] = lt[ele] + '龢'
- ss = '龢'.join(lt)
- result.append(ss.replace('龢', ' '))
- return result
- print(kao(the_words(words, maxwidth), maxwidth))
复制代码
|
|