Dwr73244
Dwr73244

Reputation: 23

Count how many words have the same beginning and ending letter/Python

QUESTION: 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.

I've tweaked this a few different ways but I still can't figure it out. Any help + explanation is appreciated so I know how to handle this the next time.

sentence = "students flock to the arb for a variety of outdoor activities 
such as jogging and picnicking"

same_letter_count = 0
sentence_split = sentence.split(' ')
sent_length = len(sentence_split)
#print(sent_length)
# Write your code here.
for d in sentence_split:
    #print(d[0])
    if d[0] == d:
        same_letter_count = same_letter_count + 1
    elif d[-1] == d:
        same_letter_count = same_letter_count + 1
print(same_letter_count)

I'm getting an answer of 1, the correct answer is 2.

Upvotes: 1

Views: 10957

Answers (4)

sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking"
same_letter_count = 0

sentence_split = sentence.split(' ')
sentense_length = len(sentence_split)

for d in sentence_split:
    if d[0] == d[-1]:
        same_letter_count += 1
print(same_letter_count)

Upvotes: 0

Mark
Mark

Reputation: 92440

You can take advantage of the fact the Python's booleans can be treated like zeros and ones and just add up all the boolean values of the test word[0] == word[-1]. The expression:

[w[0] == w[-1] for w in sentence.split()] 

evaluates to a list like [True, False, False...]. Taking the sum of that is the same as counting the number of True values and is a very typical way of doing something like this in Python.

sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking"
same_letter_count = sum(w[0] == w[-1] for w in sentence.split())
# 2

Upvotes: 6

Quang Hoang
Quang Hoang

Reputation: 150735

A quick solution by pandas:

s = pd.Series(sentence.split(' '))
(s.str[0] == s.str[-1]).sum()

gives answer 2.

You can even get those words:

s[s.str[0] == s.str[-1]]

gives:

0    students
6           a
dtype: object

Upvotes: 1

wilkben
wilkben

Reputation: 667

if d[0] == d:
    same_letter_count = same_letter_count + 1
elif d[-1] == d:
    same_letter_count = same_letter_count + 1

This checks if the first letter is equal to the entire word, or if the last letter is equal to the entire word. Therefore you are only counting "a". Instead try

if d[0] == d[-1]:
    same_letter_count = same_letter_count + 1

Upvotes: 2

Related Questions