'TwoSums code Python (Locating Indexes of Sum Values)
Could someone please explain the lines of the following code? I am having difficulty visualizing how the hash table/map stores the values. I am also confused as to how return [prevMap[diff],i]
returns the values of the indexes which correspond to the sum.
Code
List=[2,4,5,6]
target=6
class Solution:
def twosums(self, nums, target):
prevMap={} # val: index
for i, n in enumerate(nums): # key and value insertion ?
diff=target-n #
if diff in prevMap:
return [prevMap[diff],i]
prevMap[n]=i
#N=Solution()
print(Solution().twosums(List, target))
Solution 1:[1]
Some words about dict
Let's imagine that we are bosses of a big company. We want to analyze our incomes for past years. For that we need to be able to name a year to computer and receive the income for that year in response. The structure good for such a purpose is dict
(you are calling it "map"). The incomes information can be programmed like this:
incomes = {
2010: "$100.000",
2011: "$150.000",
...
2020: "$750.000",
2021: "$1.000.000"
}
If you want to know the income for year 2020
, you can simply type incomes[2020]
.
Technically, dict
just stores key: value
pairs. In the example above keys
are years and values
are incomes.
Note, that there are some restrictions:
- Each
key
should be unique. It's not possible map to store two pairskey_1: value_1
andkey_2: value_2
wherekey_1
is equal (it's not the most appropriate word here, but for simplicity let's say "equal") tokey_2
. - Each
key
should be hashable: it should provide__hash__
method and be comparable (it should provide__eq__
or__cmp__
methods). Note that in-built mutable objects (such aslist
) are not hashable. Checkout Python glossary for further details.
Your case
prevMap
is adict
which will storenumber from nums: it's index
pairs.enumerate
returns agenerator
of(index, value)
tuples. In your case it means thatn
is a number fromnums
andi
is an index ofn
in nums.diff
is a number which we can add ton
to gettarget
.- The line
prevMap[i] = n
is simply adds pairn: i
toprevMap
(if there where a pairn: another_i
this pair will be overwritten byn: i
). It allows us to remember previous values ofn
and corresponding indexes. - Expression
diff in prevMap
returnsTrue
iff there is a keydiff
inprevMap
. If it is, it means that there is a number innums
which sums up totarget
withn
and we can get its index by typingprevMap[diff]
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |