Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Storing new value to array
#1
Hi

I am new to Python and I saw this two sum algorithm solution

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        
        prevMap = {}
        
        for i, n in enumerate(nums):
            diff = target - n
            if diff in prevMap:
                return [prevMap[diff], i]
            prevMap[i] = n

In this line prevMap[i] = n I should add a value at index but it return empty array [] or should I call it map or list ? but if I use it like this prevMap[n] = i it work correctly I don understant why ? I am comming from other languages where I store new value into array like this myarray[index] = value; so python is do it in the opposit way ?
Reply
#2
The algorithm is gibberish. None of it makes sense at all.

What it is trying to do is this:
if a + b = c, then c - a = b.

Keep a record of c - a. If b appears in this record, a + b = c. In your example a dictionary (prevMap) is used to keep the record of c - a. The dictionary should have c - a as the key, and a as the value. The algorithm checks if b matches any of the dictionary keys (if b in prevMap). If it does we know that prevMap[b] + b = c (return prevMap[b], b).
Reply
#3
(Jun-22-2022, 09:10 PM)deanhystad Wrote: The algorithm is gibberish. None of it makes sense at all.

What it is trying to do is this:
if a + b = c, then c - a = b.

Keep a record of c - a. If b appears in this record, a + b = c. In your example a dictionary (prevMap) is used to keep the record of c - a. The dictionary should have c - a as the key, and a as the value. The algorithm checks if b matches any of the dictionary keys (if b in prevMap). If it does we know that prevMap[b] + b = c (return prevMap[b], b).

Can you use the the code variables above to understand ? I only dont understand last line
Reply
#4
I think he used mapping value:index to return the index for the two numbers
Reply
#5
You are probably right about that indexing thing. The dictionary is still completely wrong. Should be "prevMap[diff] = i" and "if n in prevMap"". n + diff = target
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Taking user input and storing that to a variable then storing that variable to a list jowalk 12 37,319 Mar-27-2017, 11:45 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020