r/pythonhelp • • Nov 18 '21

HOMEWORK Python exercise

Hello,

I've got the following question in my programming class, but have no idea how to solve this. Could anyone kindly explain this with a solution ?

The following Python code fills an empty dictionary d step-by-step with information on how often each letter appears in tuple t and then returns the results as seen at the end. Fill in the gaps [ ]:

d = {}

t = ('M', 'I', 'S', 'S', 'I', 'S', 'S', 'I', 'P', 'P', 'I')

[ ] b in t:

if b not in :

d[b] = 1

[ ] :

d[b] = d[b] + [ ]

[ ] b, a [ ] d.items():

print ("t includes {} {}".format( [ ], [ ]))

Output:

t includes 1 M

t includes 4 I

t includes 4 S

t includes

0 Upvotes

3 comments sorted by

1

u/[deleted] Nov 18 '21

Let me give you some help, (you need to replace the [ ] with the correct code:

d = {}  # create an empty dict, assign to d
t = ('M', 'I', 'S', 'S', 'I', 'S', 'S', 'I', 'P', 'P', 'I')

[ ] b in t:  # use a for loop to step through each letter in t
    if b not in [ ]:  # missing bit to fill in here, you need to check dictionary
        d[b] = 1  # first time you've seen letter, so add new entry with count of 1
    [ ] :  # what do if you have seen letter before?
        d[b] = d[b] + [ ]  # add 1 to existing entry in dictionary

[ ] b, a [ ] d.items():  # loop through dictionary, getting each letter and count
    print ("t includes {} {}".format( [ ], [ ]))  # output letter and count

1

u/aooooooooi Nov 28 '21

Thanks a lot !

1

u/htepO Nov 18 '21

It looks like a couple of for loops. What have you tried?