For a given string of distinct letters map each letter to a digit such that number formed is largest square possible having distinct digits.
eg:
- c – 9, a – 8, r – 0, e – 1: 9801
- h – 9, a – 6, b – 7, i – 2, t – 1: 96721
This is my code:
from math import sqrt
def sqr(n):
i = int(sqrt(n))**2
if len(set(str(i))) == len(str(i)):
return i
else:
return sqr(i-1)
s = input()
n = 10**len(s)
r = sqr(n)
for i,j in zip(s,str(r)):
print(i,j)
It takes 3-4 seconds to solve for strings of length upto 8. But after that it shows this error:
RecursionError: maximum recursion depth exceeded while getting the str of an object
Is there a better solution so that it can be done for longer strings as well?