Problem 98

completed February 16, 2012

Comments

This problem took a lot of futzing around with string methods. I used dictionaries to match numbers with letters and then replace them, returning an integer. I used the permutations iterator to give me all possible dictionaries.

What was tough is that there’s one set of three anagrams in the list. That one I dealt with separately. I first pulled the words into a list, then used combinations to copy each pair into the pairs list.

Code

from itertools import *

for words in open('words.txt','r'):
	words = words.split('","')

anagrams = []
for w in words:
	anagrams.append(''.join(sorted(w)))

pairs = []
triple = []
for i in range(len(anagrams)):
	if anagrams.count(anagrams[i]) == 2:
		try:
			pairs.append((words[i],words[anagrams.index(anagrams[i],i+1)]))
		except:
			pass
	elif anagrams.count(anagrams[i]) > 2:
		for j in range(len(anagrams)):
			if anagrams[j] == anagrams[i] and words[j] not in triple:
				triple.append(words[j])

for t in combinations(triple,2):
	pairs.append(t)

squares = []
for pair in pairs:
	for perm in permutations(range(10),len(pair[0])):
		replace_dict = dict(zip(pair[0],perm))
		pair0 = int(''.join([str(replace_dict[letter]) for letter in pair[0]]))
		pair1 = int(''.join([str(replace_dict[letter]) for letter in pair[1]]))
		if len(str(pair0)) != len(str(pair1)):
			continue
		elif (pair0**0.5)%1 != 0:
			continue
		elif (pair1**0.5)%1 != 0:
			continue
		else:
			squares.append(pair0)
			squares.append(pair1)

print max(squares)