0

how can I get this code to return a non duplicate letter? It gives a KeyError instead

def nonDuplicate(string):

    hashTable = {}

    for i in string:
        if hashTable[i]:
            return i
        else:
            hashTable[i] = True

print(nonDuplicate('minimum'))

This should return 'n', however I keep getting a KeyError for the first element. What am I missing?

3 Answers3

2

You can use get instead, which will return None if the key does not exist (rather than raising a KeyError).

if hashTable.get(i):

To be explicit that the default value is False, you can pass a second argument (as suggested by wjandrea):

if hashTable.get(i, False):
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

The KeyError is caused by the if-statement because the first letter 'm' is not in the dictionary, yet you are trying to retrieve its value. A correct approach would be to either call hashTable.get(i) or a more Pythonic way to check if i in hashTable:

Although this will solve the KeyError, I’m afraid it will not work correctly for finding the non-duplicate character. For that you will have to traverse the whole string and return the characters with exactly 1 occurrence.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
schullzroll
  • 168
  • 13
2

If i is not in hashTable, you'll get a KeyError. It's not like in some other languages like JavaScript where you get undefined out, which is falsy (Boolean(undefined) === false).

Instead, you can check if i is in hashTable, since it doesn't really matter if it's True, as long as it's present.

if i in hashTable:

However, your code doesn't actually work. The output is 'i'. You need to read the whole string to find non-duplicate characters. I recommend using a Counter:

def nonDuplicate(string):
    from collections import Counter
    c = Counter(string)
    for x, count in c.items():
        if count == 1:
            return x

print(nonDuplicate('minimum'))  # -> n

Note: If you're using Python 3.6 or lower, this might return 'u' instead of 'n' since dicts weren't necessarily order-preserving.

wjandrea
  • 28,235
  • 9
  • 60
  • 81