2
I want to create a function that returns a list with all the powers of 2 of the numbers from 0 to 99, in the shortest possible time.
So far I have performed 3 tests and my current script is this:
import timeit
import math
lista = [x for x in range(100)]
def powf(x):
return math.pow(x,2)
def teste1():
x = list(map(powf, lista))
return x
def teste2(x):
x = [powf(x) for x in lista]
return x
def teste3(y):
listareturn = []
for i in y:
listareturn.append(powf(i))
return listareturn
print('teste1')
print(timeit.timeit("teste1()", setup="from __main__ import teste1, lista", number=100000))
print('teste2')
print(timeit.timeit("teste2(lista)", setup="from __main__ import teste2, lista", number=100000))
print('teste3')
print(timeit.timeit("teste3(lista)", setup="from __main__ import teste3, lista", number=100000))
output:
teste1 = 3.0448245999999997
teste2 = 3.2884434
teste3 = 3.5317369999999997
It would be important for me to find more performative ways to write in python.
It is possible to further reduce the execution time of this function ?
numpy is very good for calculating in lists
– Elton Nunes