我给出了一个字符串列表和一个长度限制N
。我必须编写一个函数来累积列表中的连续字符串,直到下一个字符串超过N
限制。我必须返回一个列表列表,其中每个列表是不超过N
个字符总数的最大连续子字符串。
有关示例,请参阅下面的测试用例。此外,如果列表中的任何单个字符串长于N
,我必须打印一条有用的消息并返回。
def break_lst(lst, size):
def len_lst(l):
return len("".join(l))
result = []
sublst = []
for i, v in enumerate(lst):
sublst.append(v)
ls = len_lst(sublst)
if ls == size:
result.append(sublst)
sublst = []
elif ls > size:
prev_sublst = sublst[:-1]
if not prev_sublst or len_lst(prev_sublst) > size:
raise Exception("Error: use a bigger size than " + str(size))
else:
result.append(prev_sublst)
sublst = []
return result
if __name__ == "__main__":
lst = ["1", "22", "333", "4444", "55555", "666666", "7777777", "88888888"]
for i in range(17):
try:
print(i, break_lst(lst, size=i))
except Exception as e:
print(e)
以上代码不仅丑陋而且还有错误,它给了我这个输出:
Error: use a bigger size than 0
Error: use a bigger size than 1
Error: use a bigger size than 2
Error: use a bigger size than 3
Error: use a bigger size than 4
Error: use a bigger size than 5
Error: use a bigger size than 6
Error: use a bigger size than 7
8 [['1', '22', '333'], ['55555'], ['7777777']]
9 [['1', '22', '333'], ['55555'], ['7777777']]
10 [['1', '22', '333', '4444'], ['55555'], ['7777777']]
11 [['1', '22', '333', '4444'], ['666666']]
12 [['1', '22', '333', '4444'], ['666666']]
13 [['1', '22', '333', '4444'], ['666666', '7777777']]
14 [['1', '22', '333', '4444'], ['666666', '7777777']]
15 [['1', '22', '333', '4444', '55555'], ['666666', '7777777']]
16 [['1', '22', '333', '4444', '55555']]
当预期输出应为:
Error: use a bigger size than 0
Error: use a bigger size than 1
Error: use a bigger size than 2
Error: use a bigger size than 3
Error: use a bigger size than 4
Error: use a bigger size than 5
Error: use a bigger size than 6
Error: use a bigger size than 7
8 [['1', '22', '333'], ['4444'], ['55555'], ['666666'], ['7777777'], ['88888888']]
9 [['1', '22', '333'], ['4444', '55555'], ['666666'], ['7777777'], ['88888888']]
10 [['1', '22', '333', '4444'], ['55555'], ['666666'], ['7777777'], ['88888888']]
11 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
12 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
13 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
14 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
15 [['1', '22', '333', '4444', '55555'], ['666666', '7777777'], ['88888888']]
16 [['1', '22', '333', '4444', '55555'], ['666666', '7777777'], ['88888888']]
有什么建议吗?
答案 0 :(得分:2)
问题出在本节:
elif ls > size:
prev_sublst = sublst[:-1]
if not prev_sublst or len_lst(prev_sublst) > size:
raise Exception("Error: use a bigger size than " + str(size))
else:
result.append(prev_sublst)
sublst = []
您已确定下一个列表超出了给定的长度。您已正确备份了一个元素并记录了最大化的子列表。但是,您没有找到了v
元素的主页,它只会超出您的大小限制。
对于初学者,请尝试将其放入新的子列表中:
else:
result.append(prev_sublst)
sublst = [v] # <=== the change is here.
现在,检查一下你的逻辑 - 在迭代到下一个列表之前,你需要验证这个单项列表。
关于
的一个小评论for i, v in enumerate(lst):
当你从未使用过enumerate
时,为什么会遇到i
的麻烦?