1

the code:

def repeatingDigits(digits): pattern = set(digits.lstrip("0")) print(pattern)

if len(pattern) > 1:
    return(False)

if len(pattern) == 1:
  return(True)

repeatingDigits("0111") ''TRUE'' repeatingDigits("0112") ''FALSE''

  • 4
    `len(set(digits.lstrip("0"))) == 1` is easier than doing this with a regex IMO. – Samwise Feb 16 '21 at 23:49
  • @Sara Is this an exercise for learning regular expressions? – mkrieger1 Feb 16 '21 at 23:51
  • This should answer your question: [Regular expression to match any character being repeated more than 10 times](https://stackoverflow.com/questions/1660694/regular-expression-to-match-any-character-being-repeated-more-than-10-times) You only need to combine this with a regex for "zero or more times the digit 0" which should be easy to find. – mkrieger1 Feb 16 '21 at 23:55
  • 1
    This seems to be a task assignment. look at regular expression: https://docs.python.org/3/library/re.html in particular at: `0*` for loading zeroes at `\d` fr digits at `$` for end of iline at '(' and ')' for grouping, for back references (e.g. https://docs.python.org/3/library/re.html#checking-for-a-pair ) – gelonida Feb 16 '21 at 23:56
  • I can solve this problem in a different way, but my problem is that I don't know how to write it down whit the mentioned code. –  Feb 16 '21 at 23:58

1 Answers1

1

Use the regex: ^0*([1-9])\1*$

Explanation:

  • ^ : begin searching at start of string
  • 0* : search for any repeated 0's
  • ([1-9]): match digits other than 0 and remember it
  • \1* : match one or more instances of the previously matched digit
  • $ : end of string

The anchor tokens ^ and $ allow weeding out multiple occurrence of recurring digits. Python code:

import re
def repeatingDigits(digits):
    pattern = r"^0*([1-9])\1*$"
    return re.search(pattern, digits)
AnkurSaxena
  • 825
  • 7
  • 11
  • Great! I have made a change to it: ^0*(([1-9]))\1*$ –  Feb 17 '21 at 01:03
  • @Sara - great! I see you are new to SO. Consider marking an answer as accepted if it helped you. It's not obligatory though. – AnkurSaxena Feb 17 '21 at 01:06
  • yes I am new and I did not know about marking the best answer. Thanks for the explanation. Best, –  Feb 17 '21 at 04:41