codeintech3
codeintech3

Reputation: 67

Given a string, write a program that counts the number of words that begin and end with the same letter

Example: 'Two trout eat toast' would return the number 2 (trout, toast)

Here's my code so far. What would be the best way to do this program?

string = input("Enter a string ")

words = string.split()

number = 0

if (word[0].lower() == word[len(word)-1].lower()):
number += 1

print(number)

Upvotes: 0

Views: 3019

Answers (5)

vash_the_stampede
vash_the_stampede

Reputation: 4606

Here you go

example = "Two trout eat toast"
example = (example.lower()).split()

count = 0
for i in example:
    i = list(i)
    if i[0] == i[-1]:
        count += 1
print(count)

Just taking the example string, make it lower.() for comparisons, then split it and you will have the words.

After you turn each word into a list and compare the beginning and end of that list

Upvotes: 0

dsk
dsk

Reputation: 2003

If you want a simple breakdown one...

s = 'i love you Dad'
    l =[]
    l = s.split(' ')
    count = 0
    for i in l:
        if len(i)==1:
            print(i)
        else:
            if i[0].upper()==i[len(i)-1].upper():
                count = count+1
                print(i)
print(count)
Output: i
Dad
1

Upvotes: 0

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

b = a.split()                                                                                              
c = 0                                                                                                          
for item in b:                                                                                                    
    if item[0] == item[-1]:                                                                                       
        c+=1 
print(c)

Upvotes: 0

touch my body
touch my body

Reputation: 1723

If you want a one-liner:

print(sum([1 for word in input("Enter a string").lower().split() if word[0] == word[-1]]))

Upvotes: 2

Chris
Chris

Reputation: 22953

You're pretty close to what you want. You need to iterate over words to test each word:

string = input("Enter a string: ")
words = string.split()

number = 0
# iterate over `words` to test each word.
for word in words:
    # word[len(word)-1] can be replaced with just word[-1].
    if (word[0].lower() == word[-1].lower()):
        number += 1
print(number)

Running the above program with your given example produces the result:

Enter a string:  Two trout eat toast
2

Perhaps a cleaner way to do the above would be to lowercase the input string before iterating over it and using sum:

words = input("Enter a string: ").lower().split()
number = sum(word[0] == word[-1] for word in words) 
print(number) # 2

Upvotes: 4

Related Questions