I am trying to write a function to check whether a list is sorted (returning True
or False
). How can I avoid multiple variables pointing to the same thing?
def is_sorted(t):
a = t
a.sort()
When I do that, it sorts both a
and t
. How can I avoid this?
In general, it is safer to avoid aliasing when you are working with mutable objects. Of course, for immutable objects, there's no problem. That's why Python is free to alias strings and integers when it sees an opportunity to economize.
In Python, aliasing happens whenever one variable's value is assigned to another variable, because variables are just names that store references to values.
By default, Python aliases objects so that using the assignment operator makes a new variable that points to the same object; this is called an alias. Python recognizes that in some situations you want to make a copy of a mutable object, and it allows you to explicitly tell it that you want to do so.
In python programming, the second name given to a piece of data is known as an alias. Aliasing happens when the value of one variable is assigned to another variable because variables are just names that store references to actual value.
Here is the O(n) way to do it
>>> from itertools import islice, izip
>>> def is_sorted(L):
... return all(i<=j for i,j in izip(L, islice(L,1,None)))
...
>>> is_sorted(range(50))
True
>>> is_sorted(range(50)+[20])
False
It shortcircuits, so if the list is unsorted right near the beginning it will be very fast
Here is a simple program to compare some of the alternatives
import random
import time
from itertools import islice, izip
def is_sorted1(L): # 0.0006s
return all(i<=j for i,j in izip(L, islice(L,1,None)))
def is_sorted2(L): # 0.117s
return all(L[i] < L[i+1] for i in range(len(L)-1) )
def is_sorted3(L): # 2.344s
return L == sorted(L)
def is_sorted4(L): # 0.0002s
return all(L[i] < L[i+1] for i in xrange(len(L)-1) )
A = [range(random.randrange(100000)) for i in range(100)]
for a in A:
random.shuffle(a)
for f in is_sorted1, is_sorted2, is_sorted3, is_sorted4:
s=time.time()
for a in A:
f(a)
print time.time() - s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With