Python Forum
understanding some code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
understanding some code
#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


Messages In This Thread
understanding some code - by souprqtpie - Apr-02-2019, 11:16 AM
RE: understanding some code - by Larz60+ - Apr-02-2019, 11:17 AM
RE: understanding some code - by perfringo - Apr-03-2019, 10:41 AM

Forum Jump:

User Panel Messages

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