0

So my goal for this problem is to, given 2 strings, str1 and str2, create a dictionary such that the characters in str1 are the keys and the corresponding characters in str2 are the values.

ie. crackthecode('apple','byytr') returns {'a':'b','p':'y','l':'t','e':'r'} and if it is inconsistent, ie. crackthecode('apple','byptr') then returns {}, an empty dictionary.

This is my code, I'm just not sure how to do the inconsistent case.

PS. I cannot use zip for this question.

Below is my code.

def crackthecode(str1, str2):
  final = {}
  x = 0
  for i in list(str1):
    final[i]=str2[x]
    x = x + 1
  return final

All help is appreciated, thanks!

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Sania
  • 93
  • 9

1 Answers1

2

You can check if the key is already present in the dictionary, and compare the value with the new character. If they are not equal, return an empty dictionary. Otherwise, add the key-value pair to the dictionary.

You can use this code which uses the EAFP principle.

>>> def crackthecode(str1, str2):
    final = {}
    for i, key in enumerate(str1):
        try:
            if final[key] != str2[i]:
                return {}
        except KeyError:
            final[key] = str2[i]
    return final

>>> crackthecode('apple','byytr')
{'a': 'b', 'p': 'y', 'l': 't', 'e': 'r'}
>>> crackthecode('apple','byptr')
{}

Edit: Same code without using enumerate (requested by OP)

def crackthecode(str1, str2):
    final = {}
    for i in range(len(str1)):
        try:
            if final[str1[i]] != str2[i]:
                return {}
        except KeyError:
            final[str1[i]] = str2[i]
    return final 
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40