Is len O(n) or O(1) ?

P

process

Python uses arrays for lists right?

def quicksort(lista):
if lista == []:
lista
else:
return quicksort([x for x in lista[1:] if x < lista[0]]) +
[lista[0]] + \
quicksort([x for x in lista[1:] if x >= lista[0]])

or

def quicksort(lista):
if len(lista) == 0
lista
else:
return quicksort([x for x in lista[1:] if x < lista[0]]) +
[lista[0]] + \
quicksort([x for x in lista[1:] if x >= lista[0]])

wait first one raises TypeError unsupported operand types.
 
P

process

ok but if len is O(1) then it doesnt matter? compared to

if not lista:
return []

i mean.
 
S

skip

>> ok but if len is O(1) then it doesnt matter? compared to
>> if not lista:
>> return []
>> i mean.

Depends on how often the test is performed, e.g.:
... if not a: return []
... 2 0 LOAD_FAST 0 (a)
3 JUMP_IF_TRUE 5 (to 11)
6 POP_TOP
7 BUILD_LIST 0
10 RETURN_VALUE 12 LOAD_CONST 0 (None)
15 RETURN_VALUE ... if not len(a): return []
... 2 0 LOAD_GLOBAL 0 (len)
3 LOAD_FAST 0 (a)
6 CALL_FUNCTION 1
9 JUMP_IF_TRUE 5 (to 17)
12 POP_TOP
13 BUILD_LIST 0
16 RETURN_VALUE 18 LOAD_CONST 0 (None)
21 RETURN_VALUE

Even though len(a) is O(1) it's going to have a much larger constant
coefficient because of the lookup and call to len().

Skip
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,771
Messages
2,569,587
Members
45,097
Latest member
RayE496148
Top