Home > Mobile >  Find keys of dictionary that sum to 6
Find keys of dictionary that sum to 6

Time:11-06

I'm having trouble accessing multiple values in a dictionary. Let's say I have this dictionary:

{'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}

I want to find two keys that sum to 6 and display their values. Here, the keys 4 and 2 add to 6, so the 2 values are 3 and 1.

Where do I start? This is the code I have so far:

for key in dico:
        if sum(key   key) == 6:
                print(f"Numbers @ {key:dico} have a sum of 6")

CodePudding user response:

You will need to compare each of the dictionary keys with the rest of the other keys. You can use itertools for this.

As you mention you would like to print the value of each of the keys you have in your dictionary, it would be something like this:

import itertools

dico = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}

for a, b in itertools.combinations(dico.keys(), 2):
    if int(a)   int(b) == 6:
        print(f"{dico[a]} - {dico[b]}")

CodePudding user response:

No need for extra loops (or itertools), they will only slow your program down. You already know what the other index needs to be (because you can subtract the index from 6), so just check if that index exists:

dct = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}

for i, key in enumerate(dct):
    if i   2 > len(dct)/2:
        break
    
    matchIndex = str(6 - int(key))
    if dct.get(matchIndex) is not None:
        print(f'Keys {key} and {matchIndex} have values {dct[key]} and {dct[matchIndex]}')

This approach has a O(n/2) time complexity, while the other answer has O(n^2) time complexity.

When I tested this approach with timit, it took 1.72 seconds to run this answer one million times, but the itertools answer took 5.83 secondss.

CodePudding user response:

You need two loops for that.

Also, have in mind that there is more than one answer to that problem

a = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}

results = list()

for key_1 in a.keys():
  for key_2 in a.keys():
    if key_1 != key_2:
      if a[key_1]   a[key_2] == 6:
        if a[key_1] < a[key_2]:
          results.append((key_1, key_2))

print(results)
  • Related