Home > Enterprise >  Attemtping to solve twoSums leet code problem why doesn't the walrus operator with dict.get() w
Attemtping to solve twoSums leet code problem why doesn't the walrus operator with dict.get() w

Time:01-02

Prompt: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

def twoSum(nums: list, target: int) -> list:
    lookup_table = {}
    for index, num in enumerate(nums):
        if second_index := lookup_table.get(target - num):
            return [second_index, index]
        lookup_table[num] = index

I'm using python 3.10 so I know the walrus operator has been implemented. I think it has something to do with the use of returning None from the get call or the return value from lookup_table.get().

Test Case I'm using: twoSum([2,7,11,15], 9)

Currently returning: None

CodePudding user response:

The dict.get will return None if the key is not found in the dictionary. You want to check for that (note, index 0 is valid and currently in your code it will evaluate to False):

def twoSum(nums: list, target: int) -> list:
    lookup_table = {}
    for index, num in enumerate(nums):
        if (second_index := lookup_table.get(target - num)) is not None:
            return [second_index, index]
        lookup_table[num] = index



print(twoSum([2, 7, 11, 15], 9))

Prints:

[0, 1]
  • Related