Anagramic squares
Problem 98
By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square number: 1296 = 362. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: 9216 = 962. 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.
from collections import defaultdict
from tools import load_data_string_array
def anagrams(words):
data = defaultdict(list)
for word in words:
data[''.join(sorted(word))].append(word)
for key in data.keys():
if len(data[key]) < 2:
data.pop(key)
return data
def convert_dic(anagrams_dict):
data = defaultdict(list)
for values in anagrams_dict.values():
for i in range(len(values) - 1):
for j in range(i + 1, len(values)):
key = tuple(str(values[i]).index(a) for a in str(values[j]))
data[key].append((values[i], values[j]))
return data
def run():
dataA = convert_dic(anagrams(load_data_string_array(98)))
dataB = convert_dic(anagrams([str(i**2) for i in range(int((1e9)**0.5) + 1)]))
data = list(set(dataA.keys()) & set(dataB.keys()))
key = data[0]
return dataB[key][0][1]