On input we have a long list of words. And I should return an arbitrary string composed of words present in the input list and only of those. The overall length of the resulting string should be as close to 15 characters(ignoring spaces) from the lower bound (<=15) as possible. As I understood this task is connected to knapsack problem.
For example:
Input:
'This is a long string that has some words'
Output:
'This is a long that'
My function (but I have compilation error on elif statement):
def return_words(string):
MAXSYMB = 15
if not string or string.isspace():
return 'You did not enter any string'
str_ign_space = string.replace(' ', '')
elif len(str_ign_space) <= MAXSYMB:
cur_str = string.split()
return ' '.join(word for word in cur_str)
else:
a = [(i, len(i)) for i in cur_st]
sorted_items = sorted(((length, word)
for word, length in a),
reverse = True)
wt = 0
bagged = []
for length, word in sorted_items:
portion = min(MAXSYMB - wt, length)
wt += portion
bagged += [(word, portion)]
if wt >= MAXSYMB:
break
return ' '.join(item[0] for item in bagged)