Home > Net >  Write an function that takes a string and returns the number of unique characters in the string
Write an function that takes a string and returns the number of unique characters in the string

Time:11-15

I need a function using collections and maps, how can I improve this function using collection methods? The function works but needs to be modified to import collection methods.

string = str(input())
check = []
unikal = []
for i in string:
    if i in unikal:
        if not (i in check):
            check.append(i)
            del unikal[unikal.index(i)]
    else:
        if not (i in check):
            unikal.append(i)

print("Number of unique characters: ", len(unikal))

CodePudding user response:

you can use list method, count() :

unique = [i for i in input() if string.count(i) == 1]
print(len(unique))

CodePudding user response:

If you are just trying to find the number of unique characters in a string you can do something like:

x = "testymctestface"
len(set(x))

8

Note this would treat upper case as separate characters to the same letter in lower case.

This works because set creates a collection of unique inputs e.g.

x = "testymctestface"
set(x)

{'a', 'c', 'e', 'f', 'm', 's', 't', 'y'}


Update: To cache results as mentioned in the comment you could just use a dictionary e.g.

input_to_unique_char_count = {}

def get_unique_char_count(x):
    ans = input_to_unique_char_count.get(x)
    if ans is None:
       ans = len(set(x))
       input_to_unique_char_count[x] = ans
    return ans

x1 = input("type input:")
get_unique_char_count(x1)

get_unique_char_count("testtwo")
get_unique_char_count("testthree")

# you can see that the dictionary builds up the entries:
print(input_to_unique_char_count)

type input:ysyhsd
{'ysyhsd': 4, 'testtwo': 5, 'testthree': 5}

  • Related