This is the solution I came up with for solving the boggle problem. I guess it is the most "pythonic" way to do things:
from itertools import combinations
from itertools import izip
from math import fabs
def isAllowedStep(current,step,length,doubleLength):
# for step == length -1 not to be 0 => trivial solutions are not allowed
return length > 1 and \
current + step < doubleLength and current - step > 0 and \
( step == 1 or step == -1 or step <= length+1 or step >= length - 1)
def getPairwiseList(someList):
iterableList = iter(someList)
return izip(iterableList, iterableList)
def isCombinationAllowed(combination,length,doubleLength):
for (first,second) in getPairwiseList(combination):
_, firstCoordinate = first
_, secondCoordinate = second
if not isAllowedStep(firstCoordinate, fabs(secondCoordinate-firstCoordinate),length,doubleLength):
return False
return True
def extractSolution(combinations):
return ["".join([x[0] for x in combinationTuple]) for combinationTuple in combinations]
length = 4
text = tuple("".join("fxie amlo ewbx astu".split()))
textIndices = tuple(range(len(text)))
coordinates = zip(text,textIndices)
validCombinations = [combination for combination in combinations(coordinates,length) if isCombinationAllowed(combination,length,length*length)]
solution = extractSolution(validCombinations)
This part I kindly advise you not to use for all the possible matches but it would actually provide a possibility to check if the words you have generated actually constitue valid words:
import mechanize
def checkWord(word):
url = "https://en.oxforddictionaries.com/search?filter=dictionary&query="+word
br = mechanize.Browser()
br.set_handle_robots(False)
response = br.open(url)
text = response.read()
return "no exact matches" not in text.lower()
print [valid for valid in solution[:10] if checkWord(valid)]