By replacing each of the letters in the word CARE with $1, 2, 9$, and $6$ respectively, we form a square number: $1296 = 36 ^2$. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: $9216 = 96 ^2$. We shall call CARE (and RACE) a square anagram word pair and specify further that leading zeroes are not permitted, neither may a different letter have the same digital value as another letter.
Using words.txt (right click and ‘Save Link/Target As…’), a 16K text file containing nearly two-thousand common English words, find all the square anagram word pairs (a palindromic word is NOT considered to be an anagram of itself).
What is the largest square number formed by any member of such a pair?
NOTE: All anagrams formed must be contained in the given text file.
ls = open('p098_words.txt', 'r').readlines()[0].split(',')
# 判断两个字符串是否同构。 defcmp(s: str, t: str): m = len(s) for i inrange(m): for j inrange(i + 1, m): if (s[i] == s[j]) ^ (t[i] == t[j]): return0 return1
# 输入一个字符串s和其同构的字符串数t,返回s依照w对t进行重排的数。 defreplace(s: str, t: str, w: str): m = len(s) my_mp = {} for i inrange(m): my_mp[s[i]] = t[i] z = "" for i inrange(m): z += my_mp[w[i]] returnint(z)
# 预处理出pairs,所有的重排单词对。 mp, pairs = {}, [] for s in ls: s = s[1:-1] u = "".join((lambda x: (x.sort(), x)[1])(list(s))) if u notin mp.keys(): mp[u] = [] mp[u].append(s) mx_str_len = 0 for y in mp.values(): iflen(y) >= 2: m = len(y) for i inrange(m): mx_str_len = max(mx_str_len, len(y[i])) for j inrange(i + 1, m): pairs.append([y[i], y[j]]) # print(len(pairs)) mp, mq = {}, {} i = 1 whileTrue: x = i * i if x >= 10 ** mx_str_len: break s = str(x) u = "".join((lambda x: (x.sort(), x)[1])(list(s))) if u notin mp.keys(): mp[u] = [] mp[u].append(x) i += 1
for y in mp.values(): iflen(y) >= 2: for w in y: l = len(str(w)) if l notin mq.keys(): mq[l] = set() mq[l].add(w)
ans = 0 for x, y in pairs: m = len(x) if m notin mq.keys(): continue for val in mq[m]: # 不同字母必须对应不同数字。因此x和str(val)需要同构。 if cmp(x, str(val)) and replace(x, str(val), y) in mq[m]: ans = max(ans, val, replace(x, str(val), y)) print(ans)