当前位置: 代码迷 >> python >> 给定一个字符串,编写一个程序来计算以相同字母开头和结尾的单词数
  详细解决方案

给定一个字符串,编写一个程序来计算以相同字母开头和结尾的单词数

热度:81   发布时间:2023-06-19 09:15:13.0

示例:“两个鳟鱼吃吐司”将返回数字2(鳟鱼,吐司)

到目前为止,这是我的代码。 做这个程序的最好方法是什么?

string = input("Enter a string ")

words = string.split()

number = 0

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

print(number)

您非常接近所需的内容。 您需要遍历words以测试每个单词:

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)

使用给定的示例运行以上程序将产生结果:

Enter a string:  Two trout eat toast
2

也许更干净的方法是在迭代和使用sum之前将输入字符串小写。

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

如果您想要单线:

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

如果您想进行简单的分类...

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

干得好

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)

仅取example字符串,将其lower.()为进行比较,然后将其拆分,即可得到words

之后你把每一个wordlist和比较的开始和结束list

  相关解决方案