Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can someone explain why this code doesn't work? RE: string list manipulation with gross character length as criteria

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>>
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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading