The variable sentence stores a string. Write code to determine how many words in sentence start and
end with the same letter, including one-letter words. Store the result in the variable same_letter_count.
sentence = "students flock to the arb for a variety of outdoor activities such as jogging
Answers
Python code to count the no.of words in sentence which start and end with the same letter, including one-letter words.
Language used : Python Programming
Program :
sentence=list(str(input("Enter the sentence : ")).split(' '))
same_letter_count=0
for i in sentence:
if len(i)==1 or i[:1]==i[-1:]:
same_letter_count+=1
print("No. of words that starts and ends with same letter, including one-letter words are : ",same_letter_count)
Input :
Enter the sentence : students flock to the arb for a variety of outdoor activities such as jogging
Output :
No. of words that starts and ends with same letter, including one-letter words are : 2
Justification :
If we see the inputted sentence, it has only two words that starts and ends with the same letter. They are : students and a. So, the code passes the testcase and it is perfect!
Explanation :
- Take a variable named 'sentence' and input a sentence as a string and thereby, converting it into a list by stripping the letters by space, assign that list of words to the variable 'sentence'.
- Make a variable same_letter_count and assign 0 to it. Use it to assign the count.
- Write a for loop using a list with i as an iterable, that brings out each word out of a list at each iteration.
- Entering the loop, check if the length of the string in iterable i is 1. If yes, increase the count.
- If not, check whether the starting and ending letters of the string are same or not, using slicing concept. If yes, increase the count.
- Once every element in the list gets checked, the loop terminates.
- Print same_letter_count that holds the count of words in the sentence start and end with the same letter, including one-letter words. That's it!
Learn more:
- Advantages of Programming in python
brainly.in/question/11007952
- Indentation is must in python. Know more about it at :
brainly.in/question/17731168