Attenzione, questo è un po 'ricorsivo;)funzioni di temporizzazione
ho risposto a questa domanda: Python:How can i get all the elements in a list before the longest element?
E dopo ho presentato là dove un'altra risposta che dovrebbe essere più veloce (l'autore pensiero, e così feci io) . Ho provato a programmare le diverse soluzioni, ma la soluzione che dovrebbe essere più lenta era in realtà più veloce. Questo mi ha fatto pensare che ci fosse qualcosa di sbagliato nel mio codice. O è?
import string
import random
import time
def solution1(lst):
return lst[:lst.index(max(lst, key=len))]
def solution2(lst):
idx, maxLenStr = max(enumerate(lst), key=lambda x:len(x[1]))
return lst[:idx]
# Create a 100000 elements long list that contains
# random data and random element length
lst = []
for i in range(100000):
s = "".join([random.choice(string.letters+string.digits) for x in range(1, random.randint(1,50))])
lst.append(s)
# Time the first solution
start = time.time()
solution1(lst)
print 'Time for solution1', (time.time() - start)
# Time the second solution
start = time.time()
solution2(lst)
print 'Time for solution2', (time.time() - start)
Aggiornamento
Prima che qualcuno cita il motivo per cui ho messo questo è come una nuova domanda. La domanda è più su di me imparare come misurare il tempo di esecuzione ...
queste due funzioni non restituiscono lo stesso tipo di oggetto – joaquin
Doh! Certo :) Grazie! –
risolto. Ma questo rende anche il mio codice più veloce ... E ho ancora pensato che soluzione2 sia più veloce .. –