r/pythonhelp • • Oct 10 '20

Python Poetry

For the Python poetry lovers with good heart, willing to give me a hint with this poem ;) Let me know if you got BTC wallet or Patreon and I will be happy to compensate you :)

“We have developed speed, but we have shut ourselves in. Machinery that gives abundance has left us in want. Our knowledge has made us cynical. Our cleverness, hard and unkind. We think too much and feel too little. More than machinery we need humanity. More than cleverness we need kindness and gentleness.”

  1. Order all the sentences of the text according to their length (number of words per sentence) and it should be presented in the following order: the longest sentence first, the second longest thereafter and so on (e.g., ‘The longest sentence in this text contains “X” words”; The second longest sentence in this text contains “Y” words, ...., and the shortest sentence in this text contains “Z” words’).

  2. Extract five longest words in the entire text, create a List with those items and order them alphabetically. Print out these results on the screen (e.g., ‘Five longest words in this text ordered alphabetically are: “word1”, “word2”, “word3”, “word4”, “word5”’).

3 Upvotes

1 comment sorted by

2

u/sentles Oct 10 '20
s = "We have developed speed, but we have shut ourselves in. Machinery that gives abundance has left us in want. Our knowledge has made us cynical. Our cleverness, hard and unkind. We think too much and feel too little. More than machinery we need humanity. More than cleverness we need kindness and gentleness."

#Split using "." and keep non-empty strings
sentences = [sentence for sentence in s.split(".") if sentence]

#get list of all word lengths for each sentence
total_words = []
for sentence in sentences:
  total_words.append(len([word for word in sentence.split(" ") if word]))

#sort word lengths
total_words.sort(reverse = True)

#print out word lengths after they're soreted
print("Ordering sentences by word length:")
curr = 1
for length in total_words:
  print("{}. {} words".format(curr, length))
  curr += 1 

#join all sentences (dots removed) and then split them using " " as delimiter
#this results in a list, containing each word individually as a string
words = "".join(sentences).split(" ")
#sort words using length
words.sort(key = len)
#get the final 5 words (lonest words)
longest = words[:-6:-1]
#sort them alphabetically
longest.sort()

#print out the five longest words 
print("Ordering the five longest words alphabetically:")
curr = 1
for word in longest:
  print("{}. {}".format(curr, word))
  curr += 1

Here's the code. I've added comments so you can better understand what it is that it's doing. If you want to compensate me as you said, PM me.