Skip to content

Instantly share code, notes, and snippets.

@willy-r
Created December 28, 2020 07:22
Show Gist options
  • Save willy-r/e7855f5a611bbd10ba04757781512d1d to your computer and use it in GitHub Desktop.
Save willy-r/e7855f5a611bbd10ba04757781512d1d to your computer and use it in GitHub Desktop.
You’re given a string of characters that are only 2s and 0s. Return the index of the first occurrence of “2020” without using the indexOf (or similar) function, and -1 if it’s not found in the string.
def find(s: str) -> int:
if not isinstance(s, str) or not all(c in {'2', '0'} for c in s):
return -1
i = 0
while i < len(s):
if s[i:i + 4] == '2020':
return i
i += 1
return -1
def test_example():
assert find('2220000202220020200') == 14
def test_not_found():
assert find('2220000202220020220') == -1
def test_bad_inputs():
assert find(2020) == -1
assert find('123452020') == -1
if __name__ == '__main__':
test_example()
test_not_found()
test_bad_inputs()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment