【发布时间】:2022-12-01 22:44:57
【问题描述】:
Suppose I have 3 elements that I want to check if they are in an iterable say (str or list).
I'm going to use an str as an example now but it should be the same in the case of a list:
Assuming values to check for are 'a','b','c' and string to search in is 'abcd' saved in variable line.
There are "two" general ways of doing this:
One is to just do multiple checks
if 'a' in line and 'b' in line and 'c' in line:
#Do something
pass
Another is to use all
if all( sub_str in line for sub_str in ['a','b','c']):
#Do something
pass
I want to know if there is any time-complexity difference between the two approaches.
【问题讨论】:
-
Why don't you test it and determine that on your own? By the way, trying to define time complexity for such a small sample is probably not going to give you any reasonable results. remember time complexity is a measure of performance based on size of data being processed.
-
Probably worth noting that if you are doing a lot of membership lookups and are worried about performance you should be using a hashed data structure like a dict or set, rather than an iterable.
-
@JaredSmith Yes, I would normally use a set, I was just wondering about this in general. It's not related to any "real" code or anything,
-
@itprorh66 You are absolutely correct I should have tested it on my own! but as you said it won't make sense for such little data and I'm not aware of the implementations/optimizations that python does for these things (if any). That's why I asked this in case someone else knew about it.
标签: python