鱼C论坛

 找回密码
 立即注册
查看: 4179|回复: 31

[已解决]Python:每日一题 253(高额悬赏)

[复制链接]
发表于 2019-10-7 12:57:46 | 显示全部楼层 |阅读模式
20鱼币
今天的题目:


给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。

你应该使用 “贪心算法” 来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。

要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。

文本的最后一行应为左对齐,且单词之间不插入额外的空格。

说明

1. 单词是指由非空格字符组成的字符序列。
2. 每个单词的长度大于 0,小于等于 maxWidth。
3. 输入单词数组 words 至少包含一个单词。
示例 1:

输入:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
输出:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]
示例 2:

输入:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
输出:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
解释: 注意最后一行的格式应为 "shall be    " 而不是 "shall     be",
     因为最后一行应为左对齐,而不是左右两端对齐。      
     第二行同样为左对齐,这是因为这行只包含一个单词。
示例 3:

输入:
words = ["Science","is","what","we","understand","well","enough","to","explain",
         "to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
输出:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]



欢迎大家一起答题!
最佳答案
2019-10-7 12:57:47
  1. def f253(words, maxWidth):
  2.     def adjustSpace(lst):
  3.         string = ""
  4.         num_lst, len_lst = len(lst), len(''.join(lst))
  5.         if num_lst == 1:
  6.             return lst[0] + ' ' * (maxWidth - len_lst)
  7.         every_space = (maxWidth - len_lst) // (num_lst - 1)
  8.         surplus =  (maxWidth - len_lst) % (num_lst - 1)
  9.         for i in range(num_lst - 1):
  10.             string += lst[i] + ' ' * every_space
  11.             if surplus:
  12.                 string += ' '
  13.                 surplus -= 1
  14.         return string + lst[-1]

  15.     def adjustLastLine(lst):
  16.         if len(lst) == 1:
  17.             return lst[0] + ' ' * (maxWidth - len(lst[0]))
  18.         string = ' '.join(lst)
  19.         return string + ' ' * (maxWidth - len(string))

  20.     res = []
  21.     list_tmp, len_list_tmp = [], 0
  22.     for word in words:
  23.         len_word = len(word)
  24.         if len_list_tmp + len_word < maxWidth:
  25.             list_tmp.append(word)
  26.             len_list_tmp += len_word + 1
  27.         elif len_list_tmp + len_word == maxWidth:
  28.             list_tmp.append(word)
  29.             res.append(' '.join(list_tmp))
  30.             list_tmp, len_list_tmp = [], 0
  31.         else:
  32.             res.append(adjustSpace(list_tmp))
  33.             list_tmp, len_list_tmp = [word], len_word + 1
  34.     if len_list_tmp:
  35.         res.append(adjustLastLine(list_tmp))
  36.     return res
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-7 12:57:47 | 显示全部楼层    本楼为最佳答案   
  1. def f253(words, maxWidth):
  2.     def adjustSpace(lst):
  3.         string = ""
  4.         num_lst, len_lst = len(lst), len(''.join(lst))
  5.         if num_lst == 1:
  6.             return lst[0] + ' ' * (maxWidth - len_lst)
  7.         every_space = (maxWidth - len_lst) // (num_lst - 1)
  8.         surplus =  (maxWidth - len_lst) % (num_lst - 1)
  9.         for i in range(num_lst - 1):
  10.             string += lst[i] + ' ' * every_space
  11.             if surplus:
  12.                 string += ' '
  13.                 surplus -= 1
  14.         return string + lst[-1]

  15.     def adjustLastLine(lst):
  16.         if len(lst) == 1:
  17.             return lst[0] + ' ' * (maxWidth - len(lst[0]))
  18.         string = ' '.join(lst)
  19.         return string + ' ' * (maxWidth - len(string))

  20.     res = []
  21.     list_tmp, len_list_tmp = [], 0
  22.     for word in words:
  23.         len_word = len(word)
  24.         if len_list_tmp + len_word < maxWidth:
  25.             list_tmp.append(word)
  26.             len_list_tmp += len_word + 1
  27.         elif len_list_tmp + len_word == maxWidth:
  28.             list_tmp.append(word)
  29.             res.append(' '.join(list_tmp))
  30.             list_tmp, len_list_tmp = [], 0
  31.         else:
  32.             res.append(adjustSpace(list_tmp))
  33.             list_tmp, len_list_tmp = [word], len_word + 1
  34.     if len_list_tmp:
  35.         res.append(adjustLastLine(list_tmp))
  36.     return res
复制代码

评分

参与人数 1荣誉 +2 贡献 +2 收起 理由
zltzlt + 2 + 2

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-7 13:09:16 | 显示全部楼层
>>> <<<
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-7 13:14:07 | 显示全部楼层
关于算法,我并不是很懂
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-7 14:58:29 | 显示全部楼层
def solution(words, maxWidth):
    length = 0
    tmplist = list()
    res = list()
    i = 0
    while i<len(words):
        length += len(words[i])
        if length<=maxWidth:
            tmplist.append(words[i])
            i+=1
            length += 1
        else:
            newlength = 0
            for j in tmplist:
                newlength += len(j)
            tmp = ""
            if len(tmplist) != 1:
                average = (maxWidth-newlength)//(len(tmplist)-1)
                mod = (maxWidth-newlength)%(len(tmplist)-1)
                for j in range(len(tmplist)):
                    if j != len(tmplist)-1:
                        if mod != 0:
                            tmp += (tmplist[j]+" "+" "*average)
                            mod -= 1
                        else:
                            tmp += (tmplist[j]+" "*average)
                    else:
                        tmp+=(tmplist[j])
            else:
                tmp = tmplist[0] + " "*(maxWidth-newlength)
            res.append(tmp)
            length=0
            tmplist = list()
    tmp = ""
    for i in range(len(tmplist)):
        if i != len(tmplist)-1:
            tmp += (tmplist[i]+" ")
        else:
            tmp+=tmplist[i]
    tmp += " "*(maxWidth-len(tmp))
    res.append(tmp)
    return res

# 感觉写了一堆辣鸡...

点评

我很赞同!: 5.0
我很赞同!: 5
效率惊人  发表于 2019-10-7 14:59

评分

参与人数 2荣誉 +2 鱼币 +1 贡献 +1 收起 理由
zltzlt + 1 + 1
kaohsing + 1 + 1 感谢楼主无私奉献!

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-10-7 15:00:12 | 显示全部楼层
战场原 发表于 2019-10-7 14:58
def solution(words, maxWidth):
    length = 0
    tmplist = list()

恭喜通过!

执行用时:44 ms
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-7 22:51:21 | 显示全部楼层
还赶得上吗
新人来报道
不知题主想要输出列表还是文本,列表的注释掉了,这里是文本的

  1. def solve(words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16):
  2.     length = []
  3.     res = []
  4.     for each in words:
  5.         length.append(len(each))
  6.     length.append(255)
  7.     print((maxWidth - 1 - int((maxWidth-1)/2))*' '+'['+int((maxWidth-1)/2)*' ')
  8.     while len(words) > 0:
  9.         temp_words = []
  10.         l = maxWidth
  11.         counter = -1
  12.         while l > length[counter+1]:
  13.             counter += 1
  14.             l -= length[counter] + 1
  15.         temp_words = words[:counter+1]
  16.         del words[:counter+1], length[:counter+1]
  17.         ans = ''

  18.         if len(words) == 0 or counter == 0:
  19.             right = l
  20.             left = 0
  21.         else:
  22.             l += 1
  23.             right = int(l/2)
  24.             left = l - right
  25.             right -= 1

  26.         ans += ' ' * left
  27.         for each in temp_words:
  28.             ans += each + ' '
  29.         ans += ' ' * right
  30.         print(ans)
  31.         #res.append(ans)
  32.     print((maxWidth - 1 - int((maxWidth-1)/2))*' '+']'+int((maxWidth-1)/2)*' ')
  33.     #return res
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-8 00:28:58 | 显示全部楼层
  1. class WordFilling:
  2.     def __init__(self):        
  3.         self.result = list()

  4.     def fillout(self, words, max_width):
  5.         if not words:
  6.             return self.result

  7.         words_len, index = len(words), 0
  8.         row_index, temp_row = 0, list()
  9.         
  10.         while index < words_len:            
  11.             if (row_index + len(words[index])) <= max_width:
  12.                
  13.                 row_index += (len(words[index]) + 1)
  14.                 temp_row.append(words[index])
  15.                 index += 1               
  16.                 continue
  17.             
  18.             else:               
  19.                 if len(temp_row) == 1:  # 只有一个单词
  20.                     suf_space = max_width - len(temp_row[0])
  21.                     self.result.append('{0}{1}'.format(temp_row[0], ' '*suf_space))
  22.                 else:
  23.                     len_words = len(temp_row)
  24.                     total_space = max_width - row_index + len_words
  25.                     avg_space = total_space // (len_words - 1)
  26.                     pre_space = total_space % (len_words - 1)

  27.                     if pre_space > 0:
  28.                         temp = (' '*(avg_space + 1)).join(temp_row[:pre_space])
  29.                         temp += ' '*avg_space + (' '*avg_space).join(temp_row[pre_space:])
  30.                     else:
  31.                         temp = (' '*avg_space).join(temp_row)

  32.                     self.result.append(temp)

  33.                 temp_row.clear()
  34.                 row_index = 0
  35.                                                          
  36.         temp = ' '.join(temp_row)
  37.         self.result.append(temp + ' '*(max_width-len(temp_row)))
  38.         return self.result

  39. if __name__ == '__main__':
  40.    
  41.     wf = WordFilling()
  42.     words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"]
  43.     maxWidth = 20
  44.     print(wf.fillout(words, maxWidth))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-8 17:08:04 | 显示全部楼层
本帖最后由 776667 于 2019-10-8 18:08 编辑
  1. def fun253(words,maxWidth):
  2.    
  3.     def fun_x(x,maxWidth):
  4.         temp,width = [],0
  5.         x = ['%s '%i for i in x]
  6.         if sum(len(i) for i in x) < maxWidth+1:
  7.             return x
  8.         for i in range(len(x)):
  9.             width += len(x[i])
  10.             if width > maxWidth+1:
  11.                 return temp
  12.             temp.append(x[i])

  13.     groups,result = [],[]
  14.     while words:
  15.         groups.append(fun_x(words,maxWidth))
  16.         words = words[len(fun_x(words,maxWidth)):]
  17.     for i in groups:
  18.         width = sum(len(j) for j in i)
  19.         intervals = len(i)-1
  20.         if intervals == 0:
  21.             i[0] = i[0] + ' '*((maxWidth+1)-width)
  22.             result.append(i[0][:-1])
  23.         elif i == groups[-1]:
  24.             i[-1] = i[-1] + ' '*((maxWidth+1)-width)
  25.             result.append(''.join(i)[:-1])
  26.         else:
  27.             blanks = ' '*(((maxWidth+1)-width)//intervals)
  28.             remain = ((maxWidth+1)-width)%intervals
  29.             for j in range(remain):
  30.                 i[j] += ' '
  31.             result.append(blanks.join(i)[:-1])
  32.     return result
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-8 20:30:26 | 显示全部楼层
不错。学习
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-10-8 21:18:38 | 显示全部楼层
Unicorn# 发表于 2019-10-7 22:51
还赶得上吗
新人来报道
不知题主想要输出列表还是文本,列表的注释掉了,这里是文本的

解答错误,与题目示例不符,答案作废
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-10-8 21:21:24 | 显示全部楼层

解答错误,答案作废

输入:words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
输出:["This    is    an","example of text","justification.               "]
预期结果:["This    is    an","example  of text","justification.  "]
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-10-8 21:22:45 | 显示全部楼层

执行出错,答案作废

输入:words = ["ask","not","what","your","country","can","do","for","you","ask","what","you","can","do","for","your","country"], maxWidth = 16
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-8 21:33:14 | 显示全部楼层
本帖最后由 lucky邪神 于 2019-10-9 23:38 编辑

没搞懂,看大神们怎么搞
昨天留下脚印今天在办公室试了次
  1. def func253(word,maxlen):
  2.     result1=[]      #每行内容列表
  3.     result2=[]      #结果
  4.     length1=0
  5.     index =0
  6.     while index in range(len(word)):
  7.         length1 +=len(word[index])      #将word[index]加入行后,计算长度
  8.         if length1<=maxlen: #比较每行的长度与maxlen的大小
  9.             result1.append(word[index]) #将word[index]加入到行
  10.             length1 +=1         #航内容加入一个字符串后,补加一个空格
  11.             index +=1
  12.         else :      #如果加入word[index]后行长度大于maxlen,考虑换行
  13.             line=length1-len(word[index])
  14.             lenth=maxlen-line+1    #计算行长度与maxlen的差
  15.             if len(result1)==1: #如果只有一个元素
  16.                 ele=result1[0]+' '*lenth
  17.             else:
  18.                 ele=' '.join(result1[:-1]) + ' '*(lenth+1) + result1[-1]
  19.                         
  20.             result2.append(ele) #把行元素加入到结果列表
  21.             result1.clear()     #清空行列表
  22.             length1=0   #行长度归零
  23.    
  24.     lenth=maxlen-length1    #计算行长度与maxlen的差
  25.     ele=' '.join(result1) + ' '*(lenth+1)      
  26.     result2.append(ele)
  27.     return result2
复制代码

回国了,时间好紧,这么晚明天还得五点多起床上班
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-8 21:37:24 | 显示全部楼层
本帖最后由 XiaoPaiShen 于 2019-10-8 22:26 编辑
zltzlt 发表于 2019-10-8 21:21
解答错误,答案作废。

输入:words = ["This", "is", "an", "example", "of", "text", "justification ...


试试下面的代码吧
  1. class WordFilling:
  2.     def __init__(self):        
  3.         self.result = list()

  4.     def fillout(self, words, max_width):
  5.         if not words:
  6.             return self.result

  7.         words_len, index = len(words), 0
  8.         row_index, temp_row = 0, list()
  9.         
  10.         while index < words_len:            
  11.             if (row_index + len(words[index])) <= max_width:
  12.                
  13.                 row_index += (len(words[index]) + 1)
  14.                 temp_row.append(words[index])
  15.                 index += 1
  16.                
  17.                 continue
  18.             
  19.             else:               
  20.                 if len(temp_row) == 1:  # 只有一个单词
  21.                     suf_space = max_width - len(temp_row[0])
  22.                     self.result.append('{0}{1}'.format(temp_row[0], ' '*suf_space))                    
  23.                 else:
  24.                     len_words = len(temp_row)
  25.                     total_space = max_width - row_index + len_words
  26.                     avg_space = total_space // (len_words - 1)
  27.                     pre_space = total_space % (len_words - 1)

  28.                     temp = ''
  29.                     if pre_space > 0:
  30.                         for word in temp_row[:-1]:
  31.                             if pre_space > 0:
  32.                                 temp += word + ' '*(avg_space + 1)
  33.                                 pre_space -= 1
  34.                             else:
  35.                                 temp += word + ' '*(avg_space)
  36.                         temp += temp_row[-1]

  37.                     else:
  38.                         temp = (' '*avg_space).join(temp_row)

  39.                     self.result.append(temp)

  40.                 temp_row.clear()
  41.                 row_index = 0
  42.                                                          
  43.         temp = ' '.join(temp_row)
  44.         self.result.append(temp + ' '*(max_width-len(temp)))
  45.         return self.result

  46. if __name__ == '__main__':
  47.    
  48.     wf = WordFilling()
  49.     words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"]
  50.     # words =  ["This", "is", "an", "example", "of", "text", "justification."]
  51.     maxWidth = 16
  52.     print(wf.fillout(words, maxWidth))
复制代码

评分

参与人数 1荣誉 +2 鱼币 +1 贡献 +2 收起 理由
zltzlt + 2 + 1 + 2

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-8 23:49:46 | 显示全部楼层
本帖最后由 华博文 于 2019-10-9 10:29 编辑
  1. #在此处设置words值
  2. words = ["ask","not","what","your","country","can","do","for","you","ask","what","you","can","do","for","your","country"]
  3. maxWIDTH = 10


  4. pan = [each for each in words if len(each) > maxWIDTH]
  5. if not pan:
  6.     lis = list()
  7.     chu = list()
  8.     kong = " "

  9.     def qu(words , maxWIDTH , lis):
  10.         num = 0
  11.         print("len(words)  {}".format(len(words)))
  12.         for each in range(len(words)):
  13.             ding = each
  14.             num += len(words[each]) + 1
  15.             print("加到{}长度是{}\n".format(words[each]  , num))
  16.             if num > maxWIDTH and num - 1 != maxWIDTH:
  17.                 if words[0 : ding]:
  18.                     lis.append(words[0 : ding])
  19.                     words = words[ding : ]
  20.                     return qu(words , maxWIDTH , lis)
  21.                 else:
  22.                     pass
  23.             print(words[each] + " " + words[-1])
  24.             print(str(words.index(words[each])) + " " + str(len(words) - 1))
  25.             if words[each] == words[-1] and each == len(words) - 1:  
  26.                 lis.append(words[:])
  27.         return lis
  28.       
  29.     hou = qu(words , maxWIDTH , lis)
  30.     for each in range(len(hou)):
  31.         if len(hou[each]) > 1:
  32.             text = ""
  33.             xu = maxWIDTH - ((sum([len(each) for each in hou[each]]) + len(hou[each]) - 1))
  34.             mei = xu // (len(hou[each]) - 1)
  35.             yu = xu % (len(hou[each]) - 1)
  36.             if hou[each] == hou[-1]:
  37.                 for de in range(len(hou[each])):
  38.                     text += hou[each][de] + kong
  39.                 text += kong * xu
  40.                 chu.append(text)
  41.             else:
  42.                 for de in range(len(hou[each]) - 1):
  43.                     text += hou[each][de] + (kong * mei) + kong
  44.                     if yu:
  45.                         text += kong
  46.                         yu -= 1
  47.                 text += hou[each][-1]
  48.                 chu.append(text)
  49.         else:
  50.             text = ""
  51.             xu = maxWIDTH - (sum([len(each) for each in hou[each]]))
  52.             text += hou[each][0] + (kong * xu)
  53.             chu.append(text)
  54.             
  55.     print("输出结果为:")
  56.     for each in chu:
  57.         print(each)

  58.     print("列表形式:\n{}".format(chu))
  59. else:
  60.     print("您输入的值中有超过规定长度的单词~~")
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-9 00:47:39 | 显示全部楼层
重新提交......
题主您没说清楚, 我把正确的给注释掉了
重发
  1. def solve(words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16):
  2.     length = []
  3.     res = []
  4.     for each in words:
  5.         length.append(len(each))
  6.     length.append(255)
  7.     while len(words) > 0:
  8.         temp_words = []
  9.         l = maxWidth
  10.         counter = -1
  11.         while l > length[counter+1]:
  12.             counter += 1
  13.             l -= length[counter] + 1
  14.         temp_words = words[:counter+1]
  15.         del words[:counter+1], length[:counter+1]
  16.         ans = ''

  17.         if len(words) == 0 or counter == 0:
  18.             right = l
  19.             left = 0
  20.         else:
  21.             l += 1
  22.             right = int(l/2)
  23.             left = l - right
  24.             right -= 1

  25.         ans += ' ' * left
  26.         for each in temp_words:
  27.             ans += each + ' '
  28.         ans += ' ' * right
  29.         res.append(ans)
  30.     return res
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-9 12:42:42 | 显示全部楼层
本帖最后由 danteer 于 2019-10-9 13:09 编辑
  1. def func1(words,maxwidth):
  2.     print((int(maxwidth / 2) - 1) * ' ' + '[' + int(maxwidth/2) * ' ')
  3.     wordss = []
  4.     for each in words:
  5.         wordss.append(each)
  6.     while len(wordss) > 0:
  7.         length = 0
  8.         temp_word = []
  9.         counter = 0
  10.         for i in wordss:
  11.             length += len(i)
  12.             counter += 1
  13.             if length >= maxwidth:
  14.                 break
  15.             else:
  16.                 length += 1
  17.         if length == maxwidth:
  18.             for k in wordss[:counter]:
  19.                 temp_word.append(k)
  20.             del wordss[:counter]
  21.             str1 = ''
  22.             for l in temp_word:
  23.                 str1 += l + ' '
  24.             str1 = str1.rstrip()
  25.             print(str1)
  26.         elif length > maxwidth:
  27.             for j in wordss[:counter - 1]:
  28.                 temp_word.append(j)
  29.             real_length = length - len(wordss[counter - 1]) - counter + 1
  30.             del wordss[:counter - 1]
  31.             str1 = ''
  32.             if len(temp_word) == 1:
  33.                 str1 += temp_word[0] + (maxwidth - len(temp_word[0])) * ' '
  34.             else:   
  35.                 for each in temp_word:
  36.                     str1 += each + ((maxwidth - real_length) // (len(temp_word) - 1)) * ' '
  37.                 str1 = str1.rstrip()
  38.                 if len(str1) < maxwidth:
  39.                     str1 = str1[:len(temp_word[0])] + (maxwidth - len(str1)) * ' ' + str1[len(temp_word[0]):]   
  40.             print(str1)            
  41.         elif length < maxwidth:
  42.             for each in wordss:
  43.                 temp_word.append(each)
  44.             del wordss[:]
  45.             str1 = ''
  46.             for each in temp_word:
  47.                 str1 += each + ' '
  48.             str1 += (maxwidth - len(str1)) * ' '
  49.             print(str1)            
  50.     print((int(maxwidth / 2) - 1) * ' ' + ']' + int(maxwidth/2) * ' ')
复制代码

点评

我很赞同!: 5.0
我很赞同!: 5
  发表于 2019-10-9 19:42

评分

参与人数 1荣誉 +1 鱼币 +1 贡献 +1 收起 理由
zltzlt + 1 + 1 + 1

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-9 14:33:07 | 显示全部楼层







只能写到分割,后面加空格排序怎么都不会


  1. def the_words(words,maxwidth):
  2.     new_words = []
  3.     while words:
  4.         sum = 0
  5.         for each in words:   #遍历words列表中的每个元素
  6.             sum += len(each) +1   #获取每个元素的累加后的字符长度,每个字符加上一个空格['this is an ']
  7.             if sum > maxwidth:    #如果遍历累加后的长度大于分割长度maxwidth
  8.                 new_words.append(' '.join(words[0:words.index(each)]))
  9.                 words = words[words.index(each):]
  10.                 break
  11.             elif sum == maxwidth:
  12.                 new_words.append(' '.join(words[0:(words.index(each) + 1)]))
  13.                 words = words[(words.index(each) + 1):]
  14.                 break
  15.             elif sum < maxwidth and len(' '.join(words) ) < maxwidth:
  16.                 new_words.append(' '.join(words))
  17.                 words = []
  18.                 break
  19.     print(new_words)


  20. words =  ["This", "is", "an", "example", "of", "text", "justification."]
  21. maxwidth = 16

  22. the_words(words,maxwidth)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-9 15:58:09 | 显示全部楼层

关于算法,我并不是很懂
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-25 13:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表