1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| from collections import defaultdict
from time import clock
from itertools import groupby
def par_count(limots):
return sum(limots.count(mot)==1 for mot in limots)
def par_human_like(limots):
compteur = 0
vus = set([])
for i,mot in enumerate(limots):
if mot not in vus:
if mot not in limots[i+1:]:
compteur += 1
vus.add(mot)
return compteur
def par_dico_update(limots):
d = {}
[ d.update(((mot,mot not in d),)) for mot in limots ]
return sum(d.itervalues())
def par_sorting_et_groupby(limots):
limots.sort()
return sum( 1 for k,g in groupby(limots) if sum(1 for u in g)==1)
def par_sorting_et_yielding(limots):
def avance(li,k=1):
a = li[0]
for u in li[1:-1]:
if u==a: k = 0
else:
yield k
a,k = u,1
limots.sort()
return sum( avance(limots) ) + (limots[-1]!=limots[-2])
def par_defaultdict(limots):
d = defaultdict(int)
for mot in limots:
d[mot] += 1
return sum(1 for u in d.itervalues() if u==1)
def par_dictionnaire(limots):
d = {}
for mot in limots:
if mot in d:
d[mot] += 1
else:
d[mot] = 1
return sum(1 for u in d.itervalues() if u==1)
def par_dico_if(limots):
d = {}
for mot in limots:
if mot in d:
d[mot] = 0
else:
d[mot] = 1
return sum(d.itervalues())
def par_dico_if_court(limots):
d = {}
for mot in limots:
d[mot] = (mot not in d)
return sum(d.itervalues())
texte = open('akkamchi.txt').read()
fin_akkad = texte.find('FIN_AKKAD')
choisir = "\nPour choisir le texte entier (articles Akkad+Amerique+Chine, Wikipedia),\n entrer e"\
+"\nsinon pour choisir l'extrait (Akkad),\n presser ENTREE (sans aucun caractère)\n "
while True:
quoi = raw_input(choisir)
if quoi=='':
texte = texte[0:fin_akkad]
break
elif quoi=='e':
texte = texte[0:fin_akkad] + texte[fin_akkad+9:]
break
nb_essais = 10
print '\n\nNombre de mots uniques dans chaîne de '+str(len(texte))+' caractères'\
+"\n(chaque temps = le plus petit à l'issue de " + str(nb_essais) + ' exécutions) :'
for f in (par_count, par_human_like, par_dico_update, par_sorting_et_groupby, par_sorting_et_yielding,
par_defaultdict, par_dictionnaire, par_dico_if, par_dico_if_court):
cumul = []
for i in xrange(nb_essais):
li_texte = texte.split()
te = clock()
n = f(li_texte)
tf = clock()
cumul.append(tf-te)
if f==par_count and i==1:
break
print '\n' + str(f)[10:].partition(' ')[0]\
+ '\n' + str(n) + ' ' + str(n/float(len(li_texte))*100)[:5] + ' % ' + str(min(cumul)) + ' secondes' |
Partager