Search code examples
pythondictionaryhashtable

Return the only element in the hash table in Python


I am working on a problem as:

In a non-empty array of integers, every number appears twice except for one, find that single number.

I tried to work it out by the hash table:

class Solution:
    def singleNumber(self, array):
        hash = {}
        for i in array:
            if i not in hash:
                hash[i] = 0
            hash[i] += 1
            if hash[i] == 2:
                del hash[i]
        return hash.keys()


def main():
    print(Solution().singleNumber([1, 4, 2, 1, 3, 2, 3]))
    print(Solution().singleNumber([7, 9, 7]))


main()

returning the result as:

dict_keys([4])
dict_keys([9])

Process finished with exit code 0

I am not sure if there is any way that I can return only the number, e.g. 4 and 9. Thanks for your help.


Solution

  • Instead of return hash.keys() do return hash.popitem()[0] or return list(hash.keys())[0].

    Of course this assumes that there is at least one pair in the hashmap. You can check for this using len(hash) > 0 before accessing the first element:

    class Solution:
        def singleNumber(self, array):
            hash = {}
            for i in array:
                if i not in hash:
                    hash[i] = 0
                hash[i] += 1
                if hash[i] == 2:
                    del hash[i]
            return hash.popitem()[0] if len(hash) > 0 else -1  # or throw an error