Python Forum
understanding some code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
understanding some code
#1
Hello

I am currently learning how to code in python, and am doing a set of challenges set by the course I am on.
there was a certain challenge I was unable to complete, and was given the solution for. I don't understand how the solution
works for the question, and it would be great if someone could break it down for me and explain each step.

The challenge is as follows:
create a function (count) which takes a string as a parameter and returns a dictionary listing the letters in the string
and how often each occurs.
for example:

count("aa") == {"a": 2}
count("abb") == {"a": 1, "b": 2}
count("hello") == {"h": 1, "e": 1, "l": 2, "o": 1}
The solution they provided:

def count(string):
  
    out = {}
    for letter in string:
        if letter not in out:
           out[letter] = 0
        out[letter] = out[letter] + 1
    return out
Many thanks for any help, don't be afraid to be overly patronising in explanation, I won't take offence as you can't
know for sure, how solid my knowledge is. Smile

Soup
Reply
#2
def count(string):
    # Create empty dictionary out
    out = {}

    # for each letter in the string
    for letter in string:
        #if the letter's not already in the dictionary
        if letter not in out:
            # add letter to dictionary and set value to 0
            out[letter] = 0
        # now increment the letter's value
        out[letter] = out[letter] + 1
    return out
string = 'cache'
As an example structure of the dictionary for above string would look like:
out = {
    'a': 1,
    'c': 2,
    'e': 1,
    'h': 1
}
Reply
#3
(Apr-02-2019, 11:16 AM)souprqtpie Wrote: create a function (count) which takes a string as a parameter and returns a dictionary listing the letters in the string and how often each occurs.

Some alternative ways how to count letters in string using dict and it's subclasses(just for learning purposes):

>>> word = 'cache'
>>> d = {}
>>> for letter in word:
...     d[letter] = d.get(letter, 0) + 1
...
>>> d
{'c': 2, 'a': 1, 'h': 1, 'e': 1}
What dictionary method .get does: "Return the value for key if key is in the dictionary, else default". So we return value of the key if it exists or 0 if it does not and add one. It basically does same thing as original code but shorter and more concise.

>>> from collections import defaultdict
>>> word = 'cache'
>>> d = defaultdict(int)
>>> for letter in word:
...     d[letter] += 1
...
>>> d
defaultdict(int, {'c': 2, 'a': 1, 'h': 1, 'e': 1})
Python built-in module collections contain two data structures which are suitable for counting - one is defaultdict (dict subclass that calls a factory function to supply missing values) and the other is Counter (dict subclass for counting hashable objects):

>>> from collections import Counter
>>> word = 'cache'
>>> Counter(word)
Counter({'c': 2, 'a': 1, 'h': 1, 'e': 1})
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020