![](/img/trans.png)
[英]Return the number of times that the string "hi" appears anywhere in the given string -- Python codingbat problem
[英]Return the number of times that the string "code" appears anywhere in the given string
返回字符串
"code"
出现在给定字符串中任意位置的次数,除了我们接受'd'
任何字母,因此"cope"
和"cooe"
计数。
我使用正则表达式通过以下代码实现了这一点:
import re
def count_code(str):
exp = '^co[a-z|A-Z]e$'
count = 0
for i in range(len(str) - 1):
if re.match(exp, str[i:i + 4]):
count = count + 1
return count
print count_code('aaacodebbb') # prints 1
print count_code('codexxcode') # prints 2
print count_code('cozexxcope') # prints 2
有没有其他方法可以在不使用正则表达式的情况下实现这一目标?
一种方法是您可以使用 co*e 制作每个可能的字符串,其中 * 是任何字母
喜欢
x=["co"+i+"e" for i in string.lowercase]
然后迭代
for i in x:
if i in <your string>:
count+=<your string>.count(i)
你可以试试这个:
def count_code(str):
x=["co"+i+"e" for i in str.lower()]
count = 0
index = 0
for i in x:
if i in str[index:]:
index = str.find(i)+1
count+=1
return count
print count_code('aaacodebbb') # prints 1
print count_code('codexxcode') # prints 2
print count_code('cozexxcope') # prints 2
这是针对此问题的简单而干净的解决方案:
def count_code(str):
count = 0
for i in range(len(str)):
if str[i:i+2] == "co" and str[i+3:i+4] == "e":
count+=1
return count
def count_code(str):
a = 0
for i in range(len(str) - 3):
if str[i:i+2] + str[i+3] == 'coe':
a += 1
return a
您也可以尝试:使用 Python String Method 'count'
def count_code1(str):
counts=0
for i in range(97,123): #all the lowercase ASCII characters
count+= str.count('co'+chr(i)+'e')
return counts
def count_code(str):
code = 0
for c in range(len(str)-1):
if str[c+1] == 'o' and str[c:c+4:3] == 'ce':
code+=1
return code
def count_code(s):
count=0
for i in range(len(s)):
if s[-(i+3):-(i+1)]=='co' and s[-i]=='e':
count=count+1
return count
您可以以一种可以重复使用的方式定义您的逻辑 - 在这种情况下没有计数或正则表达式
def count_code(str):
start = 'co' #first 2 letter
start1 = 'e' #last letter
counter = 0 #initiate counter
strlen=len(str) #for each word
for i,x in enumerate(str):
if str[i:i+2]==start:
#for each letter - is that letter and the next equal to start
if len(str[i:strlen]) >=4: #is string long enough?
if str[i+3]==start1: # if so is last letter right?
counter+=1
else:
counter
return counter
这也应该有效:
def count_code(str):
counter = 0
for i in range(len(str)-3):
if str[i:i+2] == 'co' and str[i+3] == 'e':
counter +=1
return counter
希望能帮到你!
def count_code(str):
a=''
count=0
for char in ("abcdefghijklmnopqrstuvwxyz"):
a=char
count+=str.count("co"+a+"e")
return (count)
a = 0
for i in range(len(str)-3):
if str[i:i+2] == 'co' and str[i+3] == 'e':
a +=1
return a
def count_code(str):
count = 0
for i in range(len(str)-3):
if str[i]=='c' and str[i+1] == 'o' and str[i+3]=='e':
count+=1
return count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.