In: Computer Science
Python: Devising a secret code that maps 'one' to 'two'. We send 'o' to 't', 'n' to 'w' and 'e' to 'o'.
Can't find any code that sends 'five' to 'ten', as the words have different length.
Can't find a code that sends 'foo' to 'bar', as we would need 'o' to represent 'a' and 'r'.
Likewise we cannot send 'four' to 'aaaa', as there would be no way to map the letters back.
How would I write this Boolean function?
Write a Boolean function secret_code() that decides if we can find a code that sends one word to another and back again.
def secret_code(word1: str, word2: str) -> bool:
CODE:
def secret_code(word1: str, word2: str) -> bool:
#this is the dictionary to store the code for checking
code_map = {}
#getting the number of distinct charcters
length1 = len(set(word1))
length2 = len(set(word2))
#here are the conditions
if length1 != length2:
return False
else:
for i in range(len(word1)):
if word1[i] in code_map:
if code_map[word1[i]] != word2[i]:
return False
else:
code_map[word1[i]] = word2[i]
return True
arg1 = input("String 1:")
arg2 = input("String 2:")
print(secret_code(arg1,arg2))
_________________________________________________________________________________________________
refer this for indentation and output samples