Educative

KeyError: 'a' (Python)

I replicated the code by typing it out, and after a few checks I’m still getting an “Key Error: ‘a’” error message. Does anyone know why?

Here’s my code:

def longest_substring_with_k_distinct(str1, k):

TODO: Write your code here

window_start = 0
max_length = 0
char_frequency = {}

#I am extending the range window
for window_end in range(len(str1)):
right_char = str1[window_end]

if right_char in char_frequency:
  char_frequency[right_char] += 1
else:
  char_frequency[right_char] = 0

#Shrink the sliding window until I am left with k distinct chars in char_frequency
while len(char_frequency) > k:
left_char = str1[window_start]
char_frequency[left_char] -= 1
if char_frequency[left_char] == 0:
del char_frequency[left_char]
window_start += 1 #shrink the window

#Remember the max length thus far
max_length = max(max_length, window_end - window_start + 1)

return max_length

Hi,

I have rechecked, and the code solution is working fine. This part in your code is causing the error:

if right_char in char_frequency:
char_frequency[right_char] += 1
else:
char_frequency[right_char] = 0

right_char does not exist in the dictionary for now. Hence, this if condition will never be true. The right condition is:

if right_char not in char_frequency:
char_frequency[right_char] = 0
char_frequency[right_char] += 1

Also, else cannot be used. As once we have added a right_char in the dictionary, the ‘not in’ condition will never come true. But we still want to increment the frequency if there is another occurrence of the same right_char.

Hope that helps!