-4

I have a function that takes a string argument then it is converted to a histogram dictionary. What the function is supposed to do is compare each key which is a character to a global variable containing all the letters from the alphabet. Return a new string with the alphabet minus the characters in the dictionary. how would I accomplish this in a function using a for loop and not using counter?

alphabet = 'abcdefghi'

def histogram(s):
     d = dict()
     for c in s:
          if c not in d:
               d[c] = 1
          else:
               d[c] += 1
     return d

def missing_characters(s):
    h = histogram(s)
    global alphabet

    for c in h.keys():
        if c in alphabet:
            del h[c]

missing_characters("abc")

I get an error stating that the dictionary has changed. What I need to do is remove the given string characters from the dictionary histogram and return a new string with all the letters in order except for the ones in the string passed as an argument.

thanks in advance.

Rev3nged
  • 1
  • 2
  • That's great. Where is the function? What are the issues you face? Please give a [mcve] – roganjosh Mar 16 '19 at 14:17
  • Perhaps [this](https://stackoverflow.com/questions/7154312/how-do-i-remove-entries-within-a-counter-object-with-a-loop-without-invoking-a-r) will give you an idea. Consider using `Counter` object from `collecitons` module as it is well suited for your application. Edit: link fix – LemurPwned Mar 16 '19 at 15:10

1 Answers1

0

The problem is that - in python3 dict.keys() produces iterator over keys. You can overcome the problem by using list() instead:

alphabet = 'abcdefghi'

def histogram(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

def missing_characters(s):
    h = histogram(s)
    global alphabet

    for c in list(h):
        if c in alphabet:
            del h[c]

missing_characters("abc")
Bohdan Kaminskyi
  • 134
  • 1
  • 11
  • Thanks, I reworked a few things and used the list() on the input parameter and put alphabet through the histogram instead. Everything is working now thanks for the help and the list advice. – Rev3nged Mar 16 '19 at 15:32