Home > Software design >  How do I implement a python dictionary with combinations so that it returns keys as indices and valu
How do I implement a python dictionary with combinations so that it returns keys as indices and valu

Time:10-11

I'm trying to find 2 numbers(n=2) in the array that add up to 3 and print the tuple. In this example the output should be {0:1,1:2}. Currently I have the output to be true or false but I want it to return a tuple that is part of a dictionary and I'm not sure how to implement it.

import itertools
dict={}
def findWithSum(arr,value,n=2):
        combinations=list(itertools.combinations(arr, n))
        for t in combinations:
                
                if sum(t) == value:
                        return True
        return False     

arr= [1,2,3]
n=2
print(findWithSum(arr,3,2))

CodePudding user response:

The basic structure of your original solution works fine. To change the output into the form you're looking for, use enumerate to get tuples of the indices along with the values, make sure to sum just the values, and then return a dict of the pairs if the sum matches.

from itertools import combinations

def find_with_sum(arr: list[int], value: int, n: int = 2) -> dict[int, int]:
    for t in combinations(enumerate(arr), n):
        if sum(val for i, val in t) == value:
            return dict(t)
    return {}

print(find_with_sum([1, 2, 3], 3, 2))
# {0: 1, 1: 2}

Note that the built-in function dict very conveniently turns the combination t into the exact dict you want (it takes an iterable of tuples and gives you a dict with the first tuple element as the key and the second element of the value), but you can't use that function if you assign the name dict to something else:

dict={}  # never do this!

CodePudding user response:

import itertools
dict={}
st=set()
def findWithSum(arr,value,n=2):
        combinations=list(itertools.combinations(arr, n))
        i=0
        for t in combinations:
            st.add(t[0])
        key=0
        for i in st:
            dict[key]=i
            key =1
        return dict

arr= [1,2,3]
n=2
print(findWithSum(arr,3,2))
  • Related