Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find alternating repetitive digit pair?

121426 <- Here, 1 is an alternating repetitive digit.

523563 <- Here, NO digit is an alternating repetitive digit.

552523 <- Here, both 2 and 5 are alternating repetitive digits.

333567 <- Here, 3 is an alternating repetitive digit.

I found re.findall(r'(?=(\d)\d\1)',P) as the solution in editorial but not able to understand it.

Edit - Not allowed to use if conditions.

like image 347
Vikash Yadav Avatar asked Mar 16 '18 16:03

Vikash Yadav


Video Answer


2 Answers

You may use this regex using lookaheads:

(\d)(?=\d\1)

RegEx Demo

Explanation:

  • (\d): Match and capture a digit in group #1
  • (?=: Start lookahead
    • \d: Match any digit
    • \1: Back-reference to captured group #1
  • ): End lookahead
like image 140
anubhava Avatar answered Sep 24 '22 19:09

anubhava


You could do this without a regex using zip() in a list comprehension:

>>> s = '552523'
>>> [a for a, b in zip(s, s[2:]) if a == b]
['5', '2']
like image 36
Chris_Rands Avatar answered Sep 24 '22 19:09

Chris_Rands