Search code examples
pythonpython-3.xdictionaryfrequency

Why this python character sequence code giving unexpected result?


I am writing a python program to find character sequence in a word. But the program is giving the unexpected result. I have found a similar type program that works perfectly. To me I think the two program is quite similar but dont know why one of them does not work

  1. The program that is not working:
# Display the character sequence in a word
dict={}
string=input("Enter the string:").strip().lower()

for letter in string:
    if letter !=dict.keys():
        dict[letter]=1        
    else:
        dict[letter]=dict[letter]+1

print(dict)
  1. The program that is working:
def char_frequency(str1):
    dict = {}
    for n in str1:
        keys = dict.keys()
        if n in keys:
            dict[n] += 1
        else:
            dict[n] = 1
    return dict

print(char_frequency('google.com'))
  1. The output for the first program is giving:

Enter the string:google.com

{'g': 1, 'c': 1, 'm': 1, 'o': 1, 'l': 1, '.': 1, 'e': 1}
  1. The output for the second program is:

{'c': 1, 'e': 1, 'o': 3, 'g': 2, '.': 1, 'm': 1, 'l': 1}

The above is the correct output.

Now the questions in my mind.

i. Why the first program is not working correctly?

ii. Is the ideology of these two programs are different?


Solution

  • Actually, there's a little mistake is in the if statement you have used. Just have a look at the below modified program.

    Note: Also make sure not to use pre-defined data type names like dict as variable names. I have changed that to d here.

    >>> d = {}
    >>>
    >>> string=input("Enter the string:").strip().lower()
    Enter the string:google.com
    >>> 
    >>> for letter in string:
    ...     if letter not in d.keys():
    ...         d[letter] = 1        
    ...     else:
    ...         d[letter] = d[letter] + 1
    ... 
    >>> print(d)
    {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
    >>> 
    

    You can have also have a look at the below statements executed on the terminal.

    Comparing a key with d.keys() will always return False as key is a string here and d.keys() will always be an object of type dict_keys (Python3) and a list (Python2).

    >>> d = {"k1": "v1", "k3": "v2", "k4": "Rishi"}
    >>> 
    >>> d.keys()
    dict_keys(['k1', 'k3', 'k4'])
    >>> 
    >>> "k1" in d
    True
    >>> 
    >>> not "k1" in d
    False
    >>> 
    >>> "k1" == d.keys()
    False
    >>> 
    >>> "k1" not in d
    False
    >>>
    

    Answers of your 2 questions:

    1. Because the statement letter != dict.keys() is always True so no increment in key counts. Just change it to letter not in dict.keys(). And it is better to use d in place of dict so that the statement will look like letter not in d.keys().

    2. Logic of both the programs are same i.e. iterating over the dictionary, checking for an existence of key in dictionary. If it does not exist, create a new key with count 1 else increment the related count by 1.

    Thank you v. much.