Time complexity of in function in python [duplicate] - python

This question already has answers here:
Complexity of *in* operator in Python
(3 answers)
Closed 1 year ago.
I would like to check whether x in list(y), hence I use the code
if x in y:
return True
what is the time complexity? is it O(1) or O(n)?
Thank you

It depends on what type of object y is.
If y is a sequence type like list or tuple, the time complexity is O(n), because Python has to scan the sequence looking for a match.
If y is a hashed type like a set or dict, the time complexity is typically O(1), because Python can immediately check whether a matching object exists in the hash table.
Update: the question was edited to indicate that y is a list. In that case, the time complexity is O(n).
Also see this duplicate question and more background info.

Related

Python reverse() vs [::-1] slice performance [duplicate]

This question already has answers here:
Difference between reverse and [::-1]
(2 answers)
Time complexity of reversed() in Python 3
(1 answer)
Closed last month.
Python provides two ways to reverse a list:
List slicing notation
['a','b','c'][::-1] # ['c','b','a']
Built-in reversed() function
reversed(['a','b','c']) # ['c','b','a']
Are there any relevant differences in implementation/performance, or scenarios when one is preferred over the other?
The slicing operator constructs a new list in memory, which has implications on both memory and runtime.
reversed, on the other hand, returns an iterator which simply yields items one after another from the original list in reversed order. It does not allocate any additional memory.
So if all you're doing is iterating over the list in reverse and there's no need to construct a new (for example if you need to mutate it), then I'd say go for reversed.

Require a tuple with a certain length in python function parameters [duplicate]

This question already has answers here:
Specify length of Sequence or List with Python typing module
(4 answers)
How to limit function parameter as array of fixed-size?
(3 answers)
Closed last month.
I am writing a function that needs to take in an ordered pair coordinate (represented in a tuple). The problem is that I don't know a way to require it to have exactly two elements in the parameters of the function. Is there a better way to handle this kind of situation (like a better data type to use)? I can't think of anything.
def function(coordinate: tuple):
pass
A tuple needs to be of a given length for some non-specific function to be executed properly.
We can check the number of elements in the tuple element by using the len() function on it that comes with python directly. Wrapped in a short if condition we can only execute the said function when we have guaranteed that the given tuple has 2 elements in it. Otherwise we may print a short error message for the user.
if len(your_tuple) == 2:
function(your_tuple)
else:
print("Please enter only 2D coordinates")

How to assign two function return values to two variables and use them in the same line? [duplicate]

This question already has answers here:
Apply function to each element of a list
(4 answers)
How do I iterate through two lists in parallel?
(8 answers)
Closed 11 months ago.
Right, so this might be a rather confusing question. But in my Computer science class, we were given this optional challenge to calculate the distances a catapult has achieved after a user inputs a set of angles and speeds. But the challenge is that we have to split the problem into multiple smaller functions but each function is only allowed to have one statement per function.
I think I have a way to do it but I'm having trouble with one part.
[x = get_angles(), y = get_speeds(): 2*x[i]*y[i]/GRAVITY for i in range(len(x))]
This is part of my code for creating a list of the distances travelled. Now, this is effectively pseudo-code cause I have no clue how to make it work. Does python have anything that allows something like this to happen?
Any help would be great. Sorry for being so long-winded but thanks anyway :)
Trying to change the line of code you provided into something that works, I got this:
(lambda x, y: [2*x[i]*y[i]/GRAVITY for i in range(len(x))])(get_angles(), get_speeds())
This trick uses a lambda function to "store" the x, y values and use them in the same line.
I'm not sure this does exactly what you want, but this lambda function trick still applies.

Time complexity of converting tuple into a list (vice versa) [duplicate]

This question already has answers here:
Time complexity of casting lists to tuples in python and vice versa
(2 answers)
Closed 1 year ago.
if we are have a list lst = [1,2,3,4] and we convert it to a tuple like this tup = tuple(lst), what will be the time complexity of this code?
It is an O(N) operation, tuple(list) simply copies the objects from the list to the tuple.
so, you can still modify the internal objects(if they are mutable) but you can't add new items to the tuple
The time complexity is O(n) because the underlying operation is simply taking the original numbers and copying the objects into a tuple rather than a list.
Python list time complexity: https://wiki.python.org/moin/TimeComplexity
Operation
Average Case
Amortized Worst Case
Copy
O(n)
O(n)

Itertools Combinations/Permutations size [duplicate]

This question already has answers here:
Is there any built-in way to get the length of an iterable in python?
(10 answers)
What's the shortest way to count the number of items in a generator/iterator?
(7 answers)
Closed 4 years ago.
Is there anyway to see the len() of an itertools.Combination or other object, really, without materializing it to a list?
I can get the cardinality of combs or permutations with the factorials,... but I want something that generalizes.
Thanks
For any iterable it, you can do:
length = sum(1 for ignore in it)
That doesn't create a list, so the memory footprint is small. But for many kinds of iterables, it also consumes it (for example, if it is a generator, it's consumed and can't be restarted; if it is a list, it's not consumed). There is no generally "non-destructive" way to determine the length of an arbitrary iterable.
Also note that the code above will run "forever" if it delivers an unbounded sequence of objects.
No need to create a list. You can count the number of items in an iterable without storing the entire set:
sum(1 for _ in myIterable)
Yes,
def count_iterable(i):
return sum(1 for e in i)
Taken from: Is there any built-in way to get the length of an iterable in python?

Categories