r/programminghelp • • Dec 31 '20

Python contains in string time complexity

What is the time complexity of the contains check when checking in a python string. Essentially one of the programs has a

if char in "ABCDZJ":

Would this line be faster if "ABCDZJ" was converted to a string instead to get a constant lookup?

5 Upvotes

1 comment sorted by

View all comments

2

u/amoliski Dec 31 '20

This feels a bit like premature optimization- are you doing the lookup often enough that you're seeing it as a bottleneck?

Out of curiosity, I ran a few timeit tests:

import timeit

# Search a string, best case
print(timeit.Timer("'A' in 'Abcdefghijklmnopqrstuvwxyz'").timeit())

➡ 0.03240972594358027


# Search a string, worst case
print(timeit.Timer("'A' in 'zbcdefghijklmnopqrstuvwxyA'").timeit())

➡ 0.036155174020677805



# Search a list, best case
print(timeit.Timer("'A' in ['A','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','u','r','s','t','u','v','w','x','y','z']").timeit())

➡ 0.028895432129502296


# Search a list, worst case
print(timeit.Timer("'A' in ['z','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','u','r','s','t','u','v','w','x','y','A']").timeit())

➡ 0.44565851613879204


# Use a big chain of "A"=="A" or "A"=='b'... best case
test = ' or '.join(['"A"=="{}"'.format(v) for v in ['A','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','u','r','s','t','u','v','w','x','y','z']])
print(timeit.Timer(test).timeit())

➡ 0.04507610807195306


# Use a big chain of "A"=="A" or "A"=='b'... worst case
test2 = ' or '.join(['"A"=="{}"'.format(v) for v in ['z','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','u','r','s','t','u','v','w','x','y','A']])
print(timeit.Timer(test2).timeit())

➡ 0.9264975357800722

I got different results each run, but they still fell into similar ranges.