Python:你如何编写一个函数来计算另一个字符串s1中指定的非重叠字符串s2的出现次数?

时间:2017-04-13 06:47:20

标签: python

例如,count("系统错误,语法错误","错误")返回2。 我不确定如何编写此代码。 任何帮助是极大的赞赏。 我尝试启动代码,但在此之后我迷路了。

def main():
     s1 = input("Please enter string 1: ")
     s2 = input("Please enter string 2: ")
     print(count(s1,s2))
def count(s1, s2): # define function count that takes two strings as argument
     count = 0  # set initial count to 0

     while s2 < len(s1):

main()

5 个答案:

答案 0 :(得分:1)

  1. 您可以拆分文本并将其放入数组中:

    s= "This should work work" 
    
    words = s.split()
    
  2. 你算上这个词:

    words.count("work") 
    

答案 1 :(得分:0)

你走了:

def count(s1, s2):    # define function count that takes two strings as argument
    counter = 0    # set initial count to 0
    for i in range(len(s1)) :    # iterate over every character
        if s1[ i  : i + len(s2) ] == s2 :    # if match .. 
            counter += 1    # .. increment the counter
    return counter

One-liner:

count = lambda s1, s2 : sum([ 1 for i in range(len(s1)) if s1[ i : i + len(s2) ] == s2 ])

答案 2 :(得分:0)

考虑语句 &#34;非重叠字符串&#34;

的优化代码越多
s1 = "This is the code th fwefthe"
s2 = "th"

i = 0
len_s1, len_s2 = len(s1), len(s2)

count = 0
while i < len_s1:
   if s1[i:i+len_s2] == s2:
     count += 1
     i += len_s2
   else:
     i += 1

你可以看到,当我得到一个匹配时,计数器i增加l​​en(s2)而不是递增1。它确实提高了性能。

答案 3 :(得分:0)

我不知道是不是我,但是我认为问题写得不好,您可以在{Intro to Programing python by Daniel Liang

找到它

这是我使用Counter的解决方案:

from collections import Counter


def main():
   s1 = input("Enter first string: ").strip()
   s2 = input("Enter second string: ").strip()
   count(s1, s2)


def count(s1, s2):
  first = s1.split()
  second = s2.split()

  allElements = first + second
  newList = Counter(allElements)

  for k, v in newList.most_common(1):
      print(v)


main()

如果我用count(“ system error,语法error”)测试,它实际上返回2,无法使其与上面的答案一起使用。我的意思是测试有3个参数,计数功能有2个..Whaaa

答案 4 :(得分:0)

def twoStrings(s1, s2):
 s1 =sorted(s1)
 s2 = sorted(s2)
 i = 0
 j = 0
 result = 0
 while i < len(s1):
  while j < len(s2):
   if s1[i] == s2[j]:
    result = 1
    print ('YES')
    break
   else:
    j += 1
  j = 0
  if result == 1:
   break
  else:
   i += 1
 if result == 1: return "YES"
 else: return "NO"