It was my understanding that Python lists were implemented as vectors. That's why I can't explain why the following code is 100x slower in Python (in 3.1.3, and "only" 65x in python 3.2) than the equivalent C code.
It simply repeatedly extracts the maximum of a list, nbExtract
times :
nbValues = int(input())
nbExtract = int(input())
values = [int(value) for value in input().split()]
for loop in range(nbExtract):
idMax = 0
for idValue in range(nbValues):
if values[idMax] < values[idValue]:
idMax = idValue
print(values[idMax], end = ' ')
values[idMax] = values[nbValues- 1]
nbValues= nbValues - 1
Note : nbExtract
can be less than log(nbValues) so sorting the values is normally slower
I kown how to do it faster (using the internal max
function for example) but this was an exercise for high-school students and we are only teaching them the basics (if/else, for, while and lists), not all the functions available in Python.
Is there a way to improve the speed while keeping the same structure? I've tried Python's arrays but the speed is roughly the same.
Does anyone know why internally Python is so much slower for lists manipulation ?
As requested, equivalent C code :
#include <stdio.h>
int main()
{
int nbValues, nbExtract ;
scanf("%d%d", &nbValues, &nbExtract);
int values[nbValues];
for (int idValue = 0; idValue < nbValues; idValue++)
scanf("%d", &values[idValue]);
for (int loop = 0; loop < nbExtract; loop++)
{
int idMax = 0;
for (int idValue = 0; idValue < nbValues; idValue++)
if (values[idMax] < values[idValue])
idMax = idValue;
printf("%d ", values[idMax]);
values[idMax] = values[nbValues - 1];
nbValues--;
}
return 0;
}