Jump to content
adonisslanic

Disper

Recommended Posts

Deci pur si simplu disper:

def count(s):
d = dict()

for c in s:
d[c] += 1 + d.get(c, 0)
return d

print count(raw_input('Input the string:'))

Output:

[20:13 syn@deathstar Python]$ python2 histogram.py 
Input the string:lawl
Traceback (most recent call last):
File "histogram.py", line 8, in <module>
print count(raw_input('Input the string:'))
File "histogram.py", line 5, in count
d[c] += 1 + d.get(c, 0)
KeyError: 'l'

Link to comment
Share on other sites

De ce += (adica 2*vechea_valoare + 1) si nu doar = (vechea valoare daca exista, daca nu atunci 0, la care se adauga 1) ?

Oricum in Python pseudosuprasolicitarea operatorilor functioneaza ceva mai 1337 fata de C++, pentru ca atunci cand faci d[item] (daca item nu exista se creeaza unul cu default constructor) se returneaza o referinta catre acel obiect pe care poti face mai departe = sau += sau ce vrei tu :), pe cand in Python d[item] incearca sa-l acceseze si daca nu exista returneaza o eroare (daca e vorba de citire) in schimb daca vede ca e urmat de un = atunci se creeaza acea cheie cu valoarea din dreapta egalului, totusi daca e urmat de += asta ar insemna citirea vechii valori ce urmeaza a fi insumata cu valoarea argument si cum acel element n-ar exista din nou se returneaza eroarea.

Deci pune d[c] = d.get(c, 0) + 1 (pui un 2* daca vrei vechiul comportament).

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...