Hash Maps

It’s not really a secret that I love using hash maps, and one of my goals this week was to teach myself how to use them in Python.

Essentially, a hash map is a data structure has key/value pairs. In both Javascript and Python, to create a hash map you would create an empty object like so:
obj = {}

In JavaScript to check if your object contains an element you would say:
if (obj[elem])

But in Python, you have to check for what’s not there first, so it would be:
if num not in obj:

In both languages you increment obj[elem], marking it = 1 if it wasn’t there before, or +=1 if it was.

This creates an object which holds a key that corresponds to your array or string element, and a value that is equal to the number of times that value occurs.

When I came upon today’s algorithm exercise: “Given an array of integers, where all elements but one occur twice, find the unique element…” I knew immediately I would use a hash map.

To me, any algorithm that questions instances for unknown multiple elements = hash map. I love them because it’s a simple piece of code that’s easy to remember under pressure and can be utilized to solve many different algorithms.

Once I created my hash map like the above, I looked into ways to iterate over my obj in a one liner and came up with next(). Next() returns the next item of an iterator and when given an if statement made it so I could return the unique (single) element that had a value of 1:
return next(num for num in a if obj[num] == 1)

My final code is below. I created an object, iterated through the input array, and added in a new key/value pair or updated the value in my object. Then I iterated through it again to return the key for which the value was equal to 1:

    obj = {}
    for num in a:
        if num not in obj:
            obj[num] = 1
        else:
            obj[num] += 1      
    return next(num for num in a if obj[num] == 1)

原文链接:Hash Maps

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
The only thing standing between you and your dreams is a lot of hard work.
横跨在你和你的梦想之间的唯一的东西就是奋力拼搏
评论 抢沙发

请登录后发表评论

    暂无评论内容