There is something wrong for example in counting1("hello") instead of giving {'h': 1, 'e': 1, 'l': 2, 'o': 1} it gives me {'o': 7}
def counting1(s):
i = 1
result = {}
resultnombres = 0
if len(s) == 0:
return {}
else:
for c in s:
for j in s:
if j in c:
resultnombres += 1
result[c] = resultnombres
return result
First, Python comes with "batteries included" :-) and its standard library has everything. What you need it does to you
collections.Counter
:Second, if you want to implement it yourself to learn, your code has an error in that the line:
result[c] = resultnombres
you only do it after the loop has finishedfor c in s:
, instead of for each letter of the loop . So you only store the result of the last letter. Also, you have to reset the counterresultnombres
for each letter, instead of just once at the beginning.According to this, it should be like this:
Although this works, it is quite inefficient since you have two nested loops, so the complexity of your algorithm is O(n^2), ie it grows with the square of the size of the input string.
Another more efficient (as well as shorter) solution, which loops through the string only once, would be:
This solution can be further abbreviated if we make use of another gem from the standard library:
collections.defaultdict
which allows you to create dictionaries in which, automatically, if a key does not exist, it is added when trying to access it, instead of generating an error: