How Do You Write a Python Function to Determine if There Are Three or More Unique Characters in a String?

Problem scenario
You want a function to tell you if there are three unique characters in a string. For example "ababababa" would have fewer than three unique characters. But "abc" would have three or more unique characters. How do you write a function that does this that solves in linear time?

Solution

``````
variable_to_test = "aaaaaaaaaaaabbbbbb"

def two_unique(s):
flag = "There are only two unique characters in the string!"
dict_a = {}
for string_portion in s:
if string_portion in dict_a:
pass
else:
dict_a[string_portion] = 1
key_counter = 0
for key in dict_a.keys():
key_counter = key_counter + 1;
if key_counter > 2:
flag = True
return flag
return False

print("There are more than two unique characters!")
else:
print("There are two or fewer unique characters in the string!")``````
``````variable_to_test = "aaaaaaaaaaaabbbbbbc"

def two_unique(s):
flag = "There are only two unique characters in the string!"
dict_a = {}
for string_portion in s:
if string_portion in dict_a:
dict_a[string_portion] = dict_a[string_portion] + 1
else:
dict_a[string_portion] = 1
key_counter = 0
for key in dict_a.keys():
key_counter = key_counter + 1;
if key_counter > 2:
flag = True
return flag
return False