-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
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

4 Answers4

1

you can use regular expression with a positive lookahead for this i think

print("FOUND:",len(re.findall("([BE])(?=\\1)",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)"

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0
s=input()
for i,_ in enumerate(s):
    case s[i:i+2]:
        when "BB":
            a += 1
        when "EE":
            b += 1

Not tested, though.

Chr L
  • 89
  • 4
0

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.

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
  • Thanks for the suggestion! Sorry I didn't explain the question that well however it doesn't seem to work sometimes for example, BEEB and BEEE. I don't really understand why though, mind explaining how the code works? – Edward Jin Jun 04 '23 at 23:15
  • @EdwardJin Ok I fixed that. Problem was that `split` with explicitly given separator doesn't remove empty strings at start and end (it does when called without separator, i.e., when splitting at all whitespace). Now I'm removing them myself. But I don't like it anymore, this pushed it over an ugliness threshold for me :-) – Kelly Bundy Jun 04 '23 at 23:31
  • Ohhh alright that makes much more sense, thanks! – Edward Jin Jun 05 '23 at 01:16
0

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.

kindall
  • 178,883
  • 35
  • 278
  • 309