In this approach, we'll find out how to most efficiently determine if a string is an Isogram in Python.
The approaches page lists four idiomatic approaches to this exercise:
- Using a list comprehension and
set - Using
replaceandset - Using a
re.subandset - Using a
re.findallandset
For our performance investigation, we'll also include a fifth approach that uses a bit field to keep track of used letters.
Benchmarks
To benchmark the approaches, we wrote a small benchmark application using the timeit library.
scrubbed comprehension: 3.118929599993862e-06
scrubbed replace: 9.586393000063253e-07
scrubbed regex: 1.8171838999987813e-06
findall regex: 4.059006099996623e-06
bitfield: 5.4183307999919636e-06
The four fastest approaches use set.
- Calling a series of
replacemethods to scrub the input was the fastest approach at about 959 nanoseconds. - Next fastest was using
re.subto scrub the input, at about 1817 nanoseconds. - Third fastest was using a list comprehension to scrub the input, at about 3119 nanoseconds.
- Using
re.findallto scrub the input was fourth fastest, at about 4059 nanoseconds. - Although the bit field approach may be faster in other languages, it is significantly slower in Python.
It was slower than all of the
setapproaches, at about 5418 nanoseconds.
4th Sep 2024
·
Found it useful?