Miguel
Miguel

Reputation: 213

How to find all strings of non-negative even numbers and odd number

I'm trying to find all strings of a non-negative even number of a's followed by an odd number of b's: aab, aaaabbb, aabbb...

[w for w in words.words() if re.search('(aa|bb)$',w)][:5]

really stuck any hints that I can use?

Upvotes: 0

Views: 61

Answers (2)

Ali Nikneshan
Ali Nikneshan

Reputation: 3502

Even is 2n and Odds 2n+1 so you can implement it like this: \b(aa)*b(bb)*\b

Check This

Upvotes: 2

alecxe
alecxe

Reputation: 474091

How about you search for all a+b+ substrings and then filter them out checking how much as and bs are there in the match:

>>> import re
>>> s = "ab, aab, abb, aaaabbb, aabbb, test, ab, aabb"
>>> [item for item, a, b in re.findall(r'((a+)(b+))', s) 
     if len(a) % 2 == 0 and len(b) % 2 != 0]
['aab', 'aaaabbb', 'aabbb']

Upvotes: 1

Related Questions