【问题标题】:return True if the strings "mat" and "jet" appear the same number of times in the given string,如果字符串“mat”和“jet”在给定字符串中出现的次数相同,则返回 True,
【发布时间】:2022-01-14 06:35:45
【问题描述】:

带有最后一个元素的字符串(在此代码中为 'long' )无法进入 elif 条件...如何使其正确?

我使用的代码:

def check_occurence(string):  
    count=0 
    count1=0
    s=""
    for i in string:
        if i != " ":
             s=s+i
        elif i == " ":
            if s == 'jet' or s == 'Jet':
                count=count+1
            elif (s=='mat' or s=='Mat'):
                count1=count1+1
            s=""
    if count == count1: 
        return True 
    else: 
        return False      

string="Jet on the Mat but mat is too long"  
print(check_occurence(string))

【问题讨论】:

  • 欢迎来到 StackOverflow!请拨打tour,阅读what's on-topic hereHow to Askquestion checklist,并提供minimal reproducible example。 “为我实现此功能”与此站点无关,因为 SO 不是免费的在线编码服务。你必须诚实地尝试,然后就你的算法或技术提出一个具体问题
  • s 的初始值为 空格 (" ")。通过将字符附加到空格,永远不会得到jetJet 或任何不以空格开头的字符串。为什么不用空字符串("")初始化s
  • Tsyvarev 谢谢
  • 您正试图通过逐个字符地构建 s 来标记自己的 string; Python 是提供str.split() 方法的高级语言(试试for word in "Jet on the Mat but mat is too long".split()
  • 我的回答帮您解决了问题

标签: python string


【解决方案1】:

您可以使用 count 方法,它返回一个字符串在另一个字符串中出现的次数
像这样:

def check_occurence(str):
    return (str.count('jet')+str.count('Jet'))==(str.count('mat')+str.count('Mat'))

您只需添加字符串出现和不带首字母大写的次数并返回它们的相等性。

【讨论】:

    猜你喜欢
    • 2016-02-28
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2023-01-02
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多