4 Creating functions using regexen

 

Very often in Python, or in other programming languages, you will want to wrap a regular expression in a small function rather than repeat it inline.

Puzzle 10    Reimplementing str.count()

Summary

Create a function equivalent to str.count() using regular expressions.

The Python method str.count() is widely useful to find substrings inside a larger string. For example, here is some typical code you might write:

# Lyric from song "Hot Knife" by Fiona Apple
>>> s = """If I'm butter, if I'm butter
If I'm butter, then he's a hot knife
He makes my heart a CinemaScope screen
Showing the dancing bird of paradise
"""
>>> s.count('e')
15
>>> s.count('tt')
3

Imagine that Python did not have the method str.count() but you wished to implement a similar function by utilizing regular expressions, with the signature:

def my_count(substring: str, string: str) -> int:
    # re.sub(..., ...)  # maybe something like this?
    ...
ignore for audio

Author thoughts    How can a regex count the substring occurrences?

Two functions in the Python re module seem especially likely to be useful. The re.sub() function will replace a pattern with something else. We might try a solution using that, for example:

>>> def my_count(substring, string):
...     return len(re.sub(fr"[^{substring}]", "", string))
>>> my_count('e', s)
15
>>> my_count('tt', s)   # Oops, this goes wrong
10

AI thoughts    Extraordinary machine

Puzzle 11    Reimplementing str.count() (stricter)

Author thoughts    Write a Python function with the restrictions given

AI thoughts    The Horars of War

Puzzle 12    Finding a name for a function

Author thoughts    Code is read far more often than it is written

AI thoughts    There are two hard problems in computer science

Puzzle 13    Playing poker (Part 1)

Author thoughts    Functions are a big help in larger programs

AI thoughts    He can’t read my poker face