Find the most unique characters in a list of strings

elMatador :

Recently joined a python code club, so not a school assignment.

Task:

Write a function coolest_word(words) that returns the coolest word if it exists.

The coolness is defined by how many unique characters a word has.

For example the word "decomposition" has a 10 unique letters. Your job is to find from the given list of words the coolest word and return it.

If the list is empty, return None. If there is a tie, return one of the words.

My solution up till now:

words = ['expectation', 'discomfort', 'half', 'decomposition']
def coolest_word(words):
    length = 0
    unique = ['']
    for i in words:
        if (len(words) != 0 and len(set(i)) > length):
            length = len(set(i))
            unique[0] = i
        else:
            unique[0] = ('None')
    return(unique)  
print(coolest_word(words))

I've chosen to change list to set and afterwards compare unique characters of a set with each other. As set does not take into account duplicate variables it seemed like a good idea.

Whenever for loop finds a longer set(with more variables) it is overwritten into unique set to be memorized and later called upon.

The problem right now is that if the given list is empty unique returns [''], which I do not understand why.

As in the second part if the list is empty I want unique to be overwritten, but it does not do so.

Any thoughts?

Prashant Kumar :

If your input list words is empty, i.ee, words=[], you will not go inside the for loop. And you are not defining what should happen to unique incase input list is empty.

Try this:

words = ['expectation', 'discomfort', 'half', 'decomposition']
def coolest_word(words):
    length = 0
    unique = ['']

    if not words:    # If input list is empty set unique as None.
        unique[0] = 'None'    

    for i in words:
        if (len(words) != 0 and len(set(i)) > length):
            length = len(set(i))
            unique[0] = i
        else:
            unique[0] = ('None')
    return(unique)  
print(coolest_word(words))

But a better way I can suggest would be to initialize the unique list with None, i.e. unique = ['None'] instead of unique = ['']. This way you can keep all your code as it is.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=10202&siteId=1