adonisslanic Posted February 6, 2012 Report Share Posted February 6, 2012 Deci pur si simplu disper:def count(s): d = dict() for c in s: d[c] += 1 + d.get(c, 0) return dprint count(raw_input('Input the string:'))Output:[20:13 syn@deathstar Python]$ python2 histogram.py Input the string:lawlTraceback (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' Quote Link to comment Share on other sites More sharing options...
cmiN Posted February 7, 2012 Report Share Posted February 7, 2012 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). Quote Link to comment Share on other sites More sharing options...
adonisslanic Posted February 7, 2012 Author Report Share Posted February 7, 2012 nu era in plan acel + xD thx pentru observatie <3 Quote Link to comment Share on other sites More sharing options...