Objective
Using a loop with break statement, take a string list [headlines] and create a string list [news_ticker], wherein [news_ticker] contains (in order of precedence) the contents of [headlines] within a gross character limit of 140 characters; for the final iteration of [headlines] (i.e., the value with which its inclusion causes the gross length to meet or exceed 140 characters), if necessary, truncate the value so that the gross length does not exceed 140.
Code Attempt
headlines = ["Local Bear Eaten by Man",
"Legislature Announces New Laws",
"Peasant Discovers Violence Inherent in System",
"Cat Rescues Fireman Stuck in Tree",
"Brave Knight Runs Away",
"Papperbok Review: Totally Triffic"]
news_ticker = []
length = sum(len(chars) for chars in news_ticker)
for news in headlines:
while length < 141:
news_ticker.append(news)
else:
print(news_ticker)
break
Expected Results
>>>
Local Bear Eaten by Man Legislature Announces New Laws Peasant Discovers Violence Inherent in System Cat Rescues Fireman Stuck in Tree Brave
>>>
Actual Results
>>>
>>>
>Solution :
As length doesn’t change and values 0, you have an infinite loop here
while length < 141
You don’t want a while as you don’t want to repeat the append call, just use an if
news_ticker = []
length = sum(len(chars) for chars in news_ticker)
for news in headlines:
if length < 141:
news_ticker.append(news)
length = sum(len(chars) for chars in news_ticker)
else:
break
print(" ".join(news_ticker))
But you can just concat all, and cut
print(" ".join(headlines)[:141])
To avoid .join
result = ''
for news in headlines:
if len(result) < 141:
result += news
else:
result = result[:140]
break
print(result)