英文:
Counting the frequency of 'BB' or 'EE' in a string using Python
问题
我正在尝试计算给定字符串中某个字符串出现的次数。
我正在尝试计算'BB'或'EE'出现的次数,例如BB会返回1,而BBB会从'BBB'和B'BB'中返回2。我该如何简化这个代码?我尝试使用count
,但它只计算一次。
s = input()
for i in range(len(s) + 1):
if i > 1:
if s[i - 2:i] == 'BB':
a += 1
if s[i - 2:i] == 'EE':
b += 1
英文:
I'm trying to count every time a string appears in a given string
I'm trying to count the number of times 'BB' or 'EE' appear, for example BB would give 1, and BBB would give 2 from 'BB'B and B'BB'. How can I shorten this down? I tried using count
but it only counts it once.
s=input()
for i in range(len(s)+1):
if i>1:
if s[i-2:i]=='BB':
a+=1
if s[i-2:i]=='EE':
b+=1
答案1
得分: 1
你可以使用正向预查的正则表达式来实现这个,我认为
print("FOUND:", len(re.findall("([BE])(?=\)", text)))
[BE]
匹配B或E并将其存储... ?=
是向前预查... 它需要匹配但不消耗它... \\1
表示“匹配第一次存储的内容(要么是B要么是E)”
英文:
you can use regular expression with a positive lookahead for this i think
print("FOUND:",len(re.findall("([BE])(?=\)",text)))
[BE]
matches either B or E and stores it ... ?=
is a forward lookahead... it requires a match but does not consume it ... \\1
is saying "match that first thing you stored (either B or E)"
答案2
得分: 0
s=input()
for i,_ in enumerate(s):
case s[i:i+2]:
when "BB":
a += 1
when "EE":
b += 1
Not tested, though.
英文:
s=input()
for i,_ in enumerate(s):
case s[i:i+2]:
when "BB":
a += 1
when "EE":
b += 1
Not tested, though.
答案3
得分: 0
一个有点棘手的情况:
a = s.split('B')[1:-1].count('')
b = s.split('E')[1:-1].count('')
例如,'fooBBbarBBBquxB'.split('B')`会得到`['foo', '', 'bar', '', '', 'qux', '']`。通过B分割时,每当连续出现两个B时都会产生一个空字符串,所以我统计这些空字符串。如果字符串以B开头/结束,它还会生成一个空字符串,因此我从列表中移除第一个和最后一个元素。
英文:
A somewhat tricky one:
a = s.split('B')[1:-1].count('')
b = s.split('E')[1:-1].count('')
For example, 'fooBBbarBBBquxB'.split('B')
gives ['foo', '', 'bar', '', '', 'qux', '']
. Splitting by B gives an empty string whenever two consecutive B appear, so I count those empty strings. It also gives an empty string at start/end if the string starts/ends with B, so I remove the first and last element from the list.
答案4
得分: 0
保持跟踪循环中的上一个字符,并与当前字符一起使用,以测试是否匹配了你的字母对之一。
text = input()
lastch = ""
aa = ee = 0
for ch in text:
test = lastch + ch
aa += test == "BB"
ee += test == "EE"
lastch = ch
在循环的最后一次迭代中,lastch
(上一个字符)被初始化为空字符串,因此第一次循环时,没有上一个字符,test
不会与任何两个字符的字符串匹配,因为它只有一个字符。
英文:
Keep track of the last character you saw in the loop, and use it with the current character to test whether you have matched one of your letter pairs.
text = input()
lastch = ""
aa = ee = 0
for ch in text:
test = lastch + ch
aa += test == "BB"
ee += test == "EE"
lastch = ch
The character from the last iteration of the loop (lastch
) is initialized to an empty string, so the first time through, when there's no previous character, test
doesn't match any of the two-character strings because it only has one character.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论