Here is my practise with boggle letter square non-overlapping word finder after some drastic debugging and cleaning.
I think it is reasonable speed also. Comments wellcome.
Here is my practise with boggle letter square non-overlapping word finder after some drastic debugging and cleaning.
I think it is reasonable speed also. Comments wellcome.
10th
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
a
a&m
a&p
a's
aaa
aaas
aarhus
aaron
aau
aba
ababa
aback
abacus
abalone
abandon
abase
abash
abate
abater
abbas
abbe
abbey
abbot
abbott
abbreviate
abc
abdicate
abdomen
abdominal
abduct
abe
abed
abel
abelian
abelson
aberdeen
abernathy
aberrant
aberrate
abet
abetted
abetting
abeyance
abeyant
abhorred
abhorrent
abide
abidjan
abigail
abject
ablate
ablaze
able
ablution
abner
abnormal
abo
aboard
abode
abolish
abolition
abominable
abominate
aboriginal
aborigine
aborning
abort
abound
about
above
aboveboard
aboveground
abovementioned
abrade
abraham
abram
abramson
abrasion
abrasive
abreact
abreast
abridge
abridgment
abroad
abrogate
abrupt
abscess
abscissa
abscissae
absence
absent
absentee
absenteeism
absentia
absentminded
absinthe
absolute
absolution
absolve
absorb
absorbent
absorption
absorptive
abstain
abstention
abstinent
abstract
abstracter
abstractor
abstruse
absurd
abuilding
abundant
abusable
abuse
abusive
abut
abutted
abutting
abysmal
abyss
abyssinia
ac
academe
academia
academic
academician
academy
acadia
acanthus
acapulco
accede
accelerate
accelerometer
accent
accentual
accentuate
accept
acceptant
acceptor
access
accessible
accession
accessory
accident
accidental
accipiter
acclaim
acclamation
acclimate
accolade
accommodate
accompaniment
accompanist
accompany
accomplice
accomplish
accord
accordant
accordion
accost
account
accountant
accra
accredit
accreditate
accreditation
accretion
accrual
accrue
acculturate
accumulate
accuracy
accurate
accusation
accusative
accusatory
accuse
accustom
ace
acerbic
acerbity
acetate
acetic
acetone
acetylene
ache
achieve
achilles
aching
achromatic
acid
acidic
acidulous
ackerman
ackley
acknowledge
acknowledgeable
acm
acme
acolyte
acorn
acoustic
acquaint
acquaintance
acquiesce
acquiescent
acquire
acquisition
acquisitive
acquit
acquittal
acquitting
acre
acreage
acrid
acrimonious
acrimony
acrobacy
acrobat
acrobatic
acronym
acropolis
across
acrylate
acrylic
acs
act
actaeon
actinic
actinide
actinium
actinolite
actinometer
activate
activation
activism
acton
actor
actress
acts
actual
actuarial
actuate
acuity
acumen
acute
acyclic
ad
ada
adage
adagio
adair
adam
adamant
adams
adamson
adapt
adaptation
adaptive
add
added
addend
addenda
addendum
addict
addis
addison
addition
additional
additive
addle
address
addressee
addressograph
adduce
adelaide
adele
adelia
aden
adenine
adenoma
adenosine
adept
adequacy
adequate
adhere
adherent
adhesion
adhesive
adiabatic
adieu
adipic
adirondack
adjacent
adject
adjectival
adjective
adjoin
adjoint
adjourn
adjudge
adjudicate
adjunct
adjust
adjutant
adkins
adler
administer
administrable
administrate
administratrix
admiral
admiralty
admiration
admire
admissible
admission
admit
admittance
admitted
admitting
admix
admixture
admonish
admonition
ado
adobe
adolescent
adolph
adolphus
adonis
adopt
adoption
adoptive
adore
adorn
adposition
adrenal
adrenaline
adrian
adriatic
adrienne
adrift
adroit
adsorb
adsorbate
adsorption
adsorptive
adulate
adult
adulterate
adulterous
adultery
adulthood
advance
advantage
advantageous
advent
adventitious
adventure
adventurous
adverb
adverbial
adversary
adverse
advert
advertise
advice
advisable
advise
advisee
advisor
advisory
advocacy
advocate
aegean
aegis
aeneas
aeneid
aeolian
aeolus
aerate
aerial
aerobacter
aerobic
aerodynamic
aerogene
aeronautic
aerosol
aerospace
aeschylus
aesthete
aesthetic
afar
affable
affair
affect
affectate
affectation
affectionate
afferent
affiance
affidavit
affiliate
affine
affinity
affirm
affirmation
affirmative
affix
afflict
affluence
affluent
afford
afforest
afforestation
affricate
affront
afghan
afghanistan
aficionado
afield
afire
aflame
afloat
afoot
aforementioned
aforesaid
aforethought
afoul
afraid
afresh
africa
afro
aft
aftereffect
afterglow
afterimage
afterlife
aftermath
afternoon
afterthought
afterward
afterword
again
against
agamemnon
agate
agatha
agave
age
agee
agenda
agent
agglomerate
agglutinate
agglutinin
aggravate
aggregate
aggression
aggressive
aggressor
aggrieve
aghast
agile
aging
agitate
agleam
agnes
agnew
agnomen
agnostic
ago
agone
agony
agouti
agrarian
agree
agreeable
agreed
agreeing
agribusiness
agricola
agricultural
agriculture
agrimony
ague
agway
ah
ahead
ahem
ahmadabad
ahmedabad
ahoy
aid
aida
aide
aides
aiken
ail
ailanthus
aile
aileen
aileron
aim
ain't
ainu
air
airborne
aircraft
airdrop
airedale
aires
airfare
airfield
airflow
airfoil
airframe
airlift
airline
airlock
airmail
airman
airmass
airmen
airpark
airplane
airport
airspace
airspeed
airstrip
airtight
airway
airy
aisle
aitken
ajar
ajax
ak
akers
akin
akron
al
ala
alabama
alabamian
alabaster
alacrity
alai
alameda
alamo
alan
alarm
alaska
alb
alba
albacore
albania
albanian
albany
albatross
albeit
alberich
albert
alberta
alberto
albrecht
albright
album
albumin
albuquerque
alcestis
alchemy
alcmena
alcoa
alcohol
alcoholic
alcoholism
alcott
alcove
aldebaran
aldehyde
alden
alder
alderman
aldermen
aldrich
aldrin
ale
alec
aleck
aleph
alert
alewife
alex
alexander
alexandra
alexandre
alexandria
alexei
alexis
alfalfa
alfonso
alfred
alfredo
alfresco
alga
algae
algaecide
algal
algebra
algebraic
algenib
alger
algeria
algerian
algiers
alginate
algol
algonquin
algorithm
algorithmic
alhambra
ali
alia
alias
alibi
alice
alicia
alien
alienate
alight
align
alike
alimony
aliphatic
aliquot
alison
alistair
alive
alizarin
alkali
alkaline
alkaloid
alkane
alkene
all
allah
allan
allay
allegate
allegation
allege
allegheny
allegiant
allegoric
allegory
allegra
allegro
allele
allemand
allen
allentown
allergic
allergy
alleviate
alley
alleyway
alliance
allied
alligator
allis
allison
alliterate
allocable
allocate
allot
allotropic
allotted
allotting
allow
allowance
alloy
allspice
allstate
allude
allure
allusion
allusive
alluvial
alluvium
ally
allyl
allyn
alma
almaden
almagest
almanac
almighty
almond
almost
aloe
aloft
aloha
alone
along
alongside
aloof
aloud
alp
alpenstock
alpert
alpha
alphabet
alphabetic
alphameric
alphanumeric
alpheratz
alphonse
alpine
alps
already
alsatian
also
alsop
altair
altar
alter
alterate
alteration
altercate
alterman
altern
alternate
althea
although
altimeter
altitude
alto
altogether
alton
altruism
altruist
alum
alumina
aluminate
alumna
alumnae
alumni
alumnus
alundum
alva
alvarez
alveolar
alveoli
alveolus
alvin
alway
always
alyssum
am
ama
amadeus
amalgam
amalgamate
amanita
amanuensis
amaranth
amarillo
amass
amateur
amateurish
amatory
amaze
amazon
ambassador
amber
ambiance
ambidextrous
ambient
ambiguity
ambiguous
ambition
ambitious
ambivalent
amble
ambling
ambrose
ambrosia
ambrosial
ambulant
ambulate
ambulatory
ambuscade
ambush
amelia
ameliorate
amen
amend
amende
amerada
america
american
americana
americanism
americium
ames
ameslan
amethyst
amethystine
amherst
ami
amicable
amid
amide
amidst
amigo
amino
aminobenzoic
amiss
amity
amman
ammerman
ammeter
ammo
ammonia
ammoniac
ammonium
ammunition
amnesia
amoco
amoeba
amoebae
amok
among
amongst
amoral
amorous
amorphous
amort
amos
amount
amp
amperage
ampere
ampersand
ampex
amphetamine
amphibian
amphibious
amphibole
amphibology
amphioxis
ample
amplifier
amplify
amplitude
amply
amputate
amputee
amra
amsterdam
amtrak
amulet
amuse
amy
amygdaloid
an
ana
anabaptist
anabel
anachronism
anachronistic
anaconda
anaerobic
anaglyph
anagram
anaheim
analeptic
analgesic
analogous
analogue
analogy
analyses
analysis
analyst
analytic
anamorphic
anaplasmosis
anarch
anarchic
anarchy
anastasia
anastigmat
anastigmatic
anastomosis
anastomotic
anathema
anatole
anatomic
anatomy
ancestor
ancestral
ancestry
anchor
anchorage
anchorite
anchoritism
anchovy
ancient
ancillary
and
andean
andersen
anderson
andes
andesine
andesite
andiron
andorra
andover
andre
andrea
andrei
andrew
andrews
andromache
andromeda
andy
anecdotal
anecdote
anemone
anent
anew
angel
angela
angeles
angelfish
angelic
angelica
angelina
angeline
angelo
anger
angie
angiosperm
angle
angles
anglican
anglicanism
angling
anglo
anglophobia
angola
angora
angry
angst
angstrom
anguish
angular
angus
anharmonic
anheuser
anhydride
anhydrite
anhydrous
ani
aniline
animadversion
animadvert
animal
animate
animism
animosity
anion
anionic
anise
aniseikonic
anisotropic
anisotropy
anita
ankara
ankle
ann
anna
annal
annale
annalen
annals
annapolis
anne
anneal
annette
annex
annie
annihilate
anniversary
annotate
announce
annoy
annoyance
annual
annuity
annul
annular
annuli
annulled
annulling
annulus
annum
annunciate
anode
anodic
anomalous
anomaly
anomie
anonymity
anonymous
anorexia
anorthic
anorthite
anorthosite
another
anselm
anselmo
ansi
answer
ant
antacid
antaeus
antagonism
antagonist
antagonistic
antarctic
antarctica
antares
ante
anteater
antebellum
antecedent
antedate
antelope
antenna
antennae
anterior
anteroom
anthem
anther
anthology
anthony
anthracite
anthracnose
anthropogenic
anthropology
anthropomorphic
anthropomorphism
anti
antic
anticipate
anticipatory
antietam
antigen
antigone
antigorite
antimony
antioch
antipasto
antipathy
antiperspirant
antiphonal
antipode
antipodean
antipodes
antiquarian
antiquary
antiquated
antique
antiquity
antisemite
antisemitic
antisemitism
antithetic
antler
antoine
antoinette
anton
antonio
antony
antonym
antwerp
anus
anvil
anxiety
anxious
any
anybody
anybody'd
anyhow
anyo
from time import clock
DICT = 'unixdict.txt'
def word_path(word,used=[],pos=None):
if word:
correct_neighbour = [neigh
for p,neigh in neighbour_set
if ((pos is None or pos==p) and
(neigh not in used) and
boggle[neigh]==word[0]
)
]
for i in correct_neighbour:
used_copy=used[:]+[i]
if len(word)==1:
if boggle[i]==word:
return (used_copy,)
else:
for solution in word_path(word[1:],used_copy,pos=i):
if solution:
return (solution,)
return (False,)
neighbours=(
(-1,-1), (-1,0), (-1,1), ## above line
(0,-1), (0,1), ## same line
(1,-1), (1,0), (1,1) ## next line
)
wantquit = False
while wantquit != 'q':
boggle=''
while not boggle:
boggle=raw_input('Give your boggle:').lower() ## CATXANTXTREEEBXY
dimension=int(len(boggle)**0.5)
if dimension**2!=len(boggle):
print 'Not square boggle, give again!'
boggle=''
for i in range(dimension,len(boggle)+1,dimension):
print "%2i: %s" % (i-dimension,boggle[i-dimension:i])
neighbour_indexpairs = set(((i,j), (i+di,j+dj))
for i in range(dimension)
for j in range(dimension)
for di,dj in neighbours if 0<=dj+j<dimension and 0<=di+i<dimension
)
# change to one dimension
neighbour_set=set((a*dimension+b,c*dimension+d) for (a,b),(c,d) in neighbour_indexpairs)
t0=clock()
letterpairs = set((boggle[a]+boggle[b]) for a,b in neighbour_set)
words = set(word for word in open(DICT).read().split()
if (word.lower()==word and
len(word)>dimension-2 and
all((word[i]+word[i+1] in letterpairs) for i in range(len(word)-1))
)
)
print len(words),'candidates'
t1=clock()
result = [word for word in words
for solution in word_path(word)
if solution]
result.sort()
result.sort(key=len, reverse=True)
print "\nTotal", len(result),"solutions."
print "\nFound in %.3f ms" % (1000*(clock()-t0)),
print "of which final check took %.3f ms" % (1000*(clock()-t1))
print '\t'.join(result)
wantquit=raw_input('Ready! Push q to finish something to continue.\n').lower()
I did little optimizing after it is working and got "slightly" better performance:
(with example box: CATXANTXTREEEBXY)
Previous version:
Found in 229.725 ms of which final check took 102.581 ms
First improvements (dictionary only split once etc):
Found in 168.441 ms of which final check took 46.105 ms
This version:
Found in 127.655 ms of which final check took 5.148 ms
from time import clock
DICT = 'unixdict.txt'
def word_path(word,used=[],pos=None):
if word:
correct_neighbour = [neigh
for neigh in (neighbourlist[pos] if pos else range(dimension*dimension))
if ((neigh not in used) and
boggle[neigh]==word[0])
]
for i in correct_neighbour:
used_copy=used[:]+[i]
if len(word)==1:
if boggle[i]==word:
return (used_copy,)
else:
for solution in word_path(word[1:],used_copy,pos=i):
if solution:
return (solution,)
return (False,)
neighbours=(
(-1,-1), (0,-1), (1,-1), ## left column
(-1,0), (1,0), ## same column
(-1,1), (0,1), (1,1) ## next column
)
wordlist=open(DICT).read().split()
wantquit = False
while wantquit != 'q':
boggle=''
while not boggle:
boggle=raw_input('Give your boggle:').lower() ## CATXANTXTREEEBXY
dimension=int(len(boggle)**0.5)
if dimension**2!=len(boggle):
print 'Not square boggle, give again!'
boggle=''
for i in range(0,len(boggle)-dimension+1,dimension):
print "%2i: %s" % (i,boggle[i:i+dimension])
neighbour_indexpairs = set(((i,j), (i+di,j+dj))
for i in range(dimension)
for j in range(dimension)
for di,dj in neighbours if 0<=dj+j<dimension and 0<=di+i<dimension
)
# change to one dimension
neighbour_set=set((a*dimension+b,c*dimension+d) for (a,b),(c,d) in neighbour_indexpairs)
neighbourlist = [[] for _ in boggle]
[neighbourlist[char_index].append(b) for char_index,b in neighbour_set]
t0=clock()
letterpairs = set((boggle[a]+boggle[b]) for a,b in neighbour_set)
words = set(word for word in wordlist
if (word.lower()==word and
len(word)>dimension-2 and
all((word[i]+word[i+1] in letterpairs) for i in range(len(word)-1))
)
)
print len(words),'candidates'
t1=clock()
result = [word for word in words
for solution in word_path(word)
if solution]
result.sort()
result.sort(key=len, reverse=True)
print "\nTotal", len(result),"solutions."
print "\nFound in %.3f ms" % (1000*(clock()-t0)),
print "of which final check took %.3f ms" % (1000*(clock()-t1))
print '\t'.join(result)
wantquit=raw_input('Ready! Push q to finish something to continue.\n').lower()
Line 7 should be
for neigh in (neighbourlist[pos] if pos is not None else range(dimension*dimension))
0 is valid index of neighbour list.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.