COSI 2a Lecture 7: COSI Week 7
64 views4 pages
17 Mar 2017
School
Department
Course
Professor
Document Summary
Get the longest words in a sentence write a function, getlongestword(sentence), which accepts a string sentence and returns the longest word in the sentence. If there are multiple longest words of the same length, it should choose the first. Your function should use the split method to convert sentence into a list of words as follows: words = sentence. split() Solution: def getlongestword(sentence): words=sentence. split() longestword=words[0] for x in words: if len(x)>len(longestword): longestword=x return longestword. Count words write a function, countword(sentence,word), which accepts two strings, (sentence and word) and returns the number of times that word appears in the sentence. Your function should use the split method to convert sentence into a list of words as follows: words = sentence. split() and initialize a counter variable: counter=0 which it increments each time it see the word in a loop. Solution: def countword(sentence,word): counter=0 words=sentence. split() for x in words: if (x==word): counter=counter+1 return counter.
Get access
Grade+
$40 USD/m
Billed monthly
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers