Как соединить предложения в выражение, чтобы выражение не превышало 400 символов?
Задача в том, чтобы элементы списка ( предложения ) соединялись в выражения из предложений. И нужно чтобы эти выражения не превышали 400 символов. К примеру, мы получаем на вход список ['abc', 'bc', 'c', 'a', 'r', 's' ], на выходе получаем [ 'abc', 'bcc', 'ars' ] ( если у нас не превышает 3 ), а нам нужно также только не превышает 400 символов.
Исходный код: https://github.com/textil24/divider_400/blob/main/divider_400.py
def divider_400():
list = ['Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.',
'Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.',
"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.",
'Python supports modules and packages, which encourages program modularity and code reuse.',
'The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.', 'Often, programmers fall in love with Python because of the increased productivity it provides.',
'Since there is no compilation step, the edit-test-debug cycle is incredibly fast.', 'Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault.', 'Instead, when the interpreter discovers an error, it raises an exception.', "When the program doesn't catch the exception, the interpreter prints a stack trace.",
'A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on.', "The debugger is written in Python itself, testifying to Python's introspective power.",
'On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.'
]
new_list_1 = []
new_list_2 = []
new_list_3 = []
new_list_4 = []
count = 0
for item in list:
count += len(item)
if count <= 400:
new_list_1.append(item)
elif count <= 800:
new_list_2.append(item)
elif count <= 1200:
new_list_3.append(item)
elif count <= 1600:
new_list_4.append(item)
main_list = []
res1 = ' '.join(new_list_1)
res2 = ' '.join(new_list_2)
res3 = ' '.join(new_list_3)
res4 = ' '.join(new_list_4)
res_list = [res1, res2, res3, res4]
for item in res_list:
main_list.append(item)
return [x for x in main_list if x.strip()]
result_text = divider_400()
for item in result_text:
print(len(item))
Ответы (2 шт):
Объедините элементы списка в одну строку и разбейте ее на слова
Далее сделайте пустую строку, и добавляйте в нее слова, пока общая длина меньше 400
Когда полученная длина станет больше 400, занесите ее в новый список, и очистите, и так по кругу.
lst = ['Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.', 'Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.', "Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.", 'Python supports modules and packages, which encourages program modularity and code reuse.', 'The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.', 'Often, programmers fall in love with Python because of the increased productivity it provides.', 'Since there is no compilation step, the edit-test-debug cycle is incredibly fast.', 'Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault.', 'Instead, when the interpreter discovers an error, it raises an exception.', "When the program doesn't catch the exception, the interpreter prints a stack trace.", 'A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on.', "The debugger is written in Python itself, testifying to Python's introspective power.", 'On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.' ] list_array = [] current_str = "" for word in "".join(lst).split(): if len(current_str) + len(word) < 400: current_str += word else: list_array.append(current_str) current_str = "" for el in list_array: print(el)
Поскольку в задании не указано явно, что слова в выражениях не должны дробиться , то нет нужды перебирать все слова. Можно сразу склеить все в одну строку, а затем перебрать в цикле целочисленным делителем, полученным отношением длины текста к 400.
def divider_400():
list = ['Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.',
'Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.',
"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.",
'Python supports modules and packages, which encourages program modularity and code reuse.',
'The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.',
'Often, programmers fall in love with Python because of the increased productivity it provides.',
'Since there is no compilation step, the edit-test-debug cycle is incredibly fast.',
'Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault.',
'Instead, when the interpreter discovers an error, it raises an exception.',
"When the program doesn't catch the exception, the interpreter prints a stack trace.",
'A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on.',
"The debugger is written in Python itself, testifying to Python's introspective power.",
'On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.'
]
text = ' '.join(list)
count = len(text) // 400
slice_start = 0
slice_end = 400
list = []
for _ in range(count):
list.append(text[slice_start: slice_end])
slice_start += 400
slice_end += 400
list.append(text[slice_start:])
return list
result_text = divider_400()
for item in result_text:
print(len(item))
А если слова не должны дробиться, то можно добавить проверку на срез методом endswith()