Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Attemtping to solve twoSums leet code problem why doesn't the walrus operator with dict.get() work in python3

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading