0

As I told before here is second implementation of one word anagrams, which prepares lookup table for all available words, if it is not generated and afterwards uses it for fast lookup.

The implementation of lookup table generation is quite unoptimized, but it is only done once per vocabulary.

If you want to change dictionary, add dictionary selection routine instead of fixed one here or just rename/delete old dictionary and anawords and analist files. Then make copy of your dictionary in same dictionary as this program with name list.txt.

First run:

Dict prepared in 0.726 s
Dict saved for future
Preparations took 0.889 s
Output:
Saved dict loaded
Preparations took 0.132 s
To stop: enter empty line
Give word: meti
['emit', 'item', 'mite', 'time']
0 ms
Give word: ewd
['dew', 'wed', "we'd"]
0 ms
Give word: team
['mate', 'meat', 'tame', 'team']
0 ms
Give word: mocupret
['computer']
0 ms
Give word: nocpurte
Word is not in vocabulary
0 ms
Give word:

Edited by pyTony: First run output

Attachments
a
aardvark
abaci
aback
abacus
abaft
abalone
abandon
abandoned
abandonment
abase
abasement
abash
abashed
abashedly
abashment
abate
abatement
abattoir
abbe
abbess
abbey
abbot
abbreviate
abbreviated
abbreviation
abdicate
abdication
abdomen
abdominal
abduct
abduction
abductor
abeam
abed
aberrant
aberration
aberrational
abet
abetter
abettor
abeyance
abhor
abhorrence
abhorrent
abhorrently
abidance
abide
abiding
abidingly
ability
abject
abjection
abjectly
abjectness
abjuration
abjuratory
abjure
abjurer
ablate
ablation
ablative
ablaze
able
able-bodied
abloom
ablution
ablutions
ably
abnegate
abnegation
abnormal
abnormality
abnormally
aboard
abode
abolish
abolition
abolitionism
abolitionist
abominable
abominably
abominate
abomination
aboriginal
aborigine
aborning
abort
abortion
abortionist
abortive
abortively
abound
about
about-face
above
aboveboard
above-mentioned
abracadabra
abrade
abrasion
abrasive
abrasively
abrasiveness
abreast
abridge
abridgement
abridgment
abroad
abrogate
abrogation
abrogator
abrupt
abruptly
abruptness
abs
abscess
abscessed
abscissa
abscissae
abscission
abscond
absconder
absence
absent
absentee
absenteeism
absently
absentminded
absentmindedly
absentmindedness
absinth
absinthe
absolute
absolutely
absoluteness
absolution
absolutism
absolutist
absolve
absorb
absorbed
absorbency
absorbent
absorbing
absorbingly
absorption
absorptive
abstain
abstainer
abstemious
abstemiously
abstemiousness
abstention
abstinence
abstinent
abstract
abstracted
abstractedly
abstractedness
abstraction
abstractly
abstractness
abstruse
abstrusely
abstruseness
absurd
absurdity
absurdly
absurdness
abundance
abundant
abundantly
abuse
abuser
abusive
abusively
abusiveness
abut
abutment
abuzz
abysmal
abysmally
abyss
abyssal
acacia
academe
academia
academic
academically
academician
academics
academy
acanthus
accede
accelerate
acceleration
accelerator
accent
accented
accentual
accentuate
accentuation
accept
acceptability
acceptable
acceptableness
acceptably
acceptance
acceptation
accepted
access
accessibility
accessible
accessibly
accession
accessory
accident
accidental
accidentally
accident-prone
acclaim
acclaimed
acclamation
acclimate
acclimation
acclimatization
acclimatize
acclivity
accolade
accommodate
accommodating
accommodatingly
accommodation
accommodations
accompaniment
accompanist
accompany
accomplice
accomplish
accomplished
accomplishment
accord
accordance
accordant
according
accordingly
accordion
accordionist
accost
account
accountability
accountable
accountancy
accountant
accounting
accounts
accouter
accouterments
accoutre
accoutrements
accredit
accreditation
accredited
accretion
accrual
accrue
acculturate
acculturation
accumulate
accumulation
accumulative
accumulator
accuracy
accurate
accurately
accurateness
accursed
accursedness
accusation
accusative
accusatory
accuse
accused
accuser
accusingly
accustom
accustomed
ace
acerbate
acerbic
acerbically
acerbity
acetaminophen
acetate
acetic
acetone
acetonic
acetylene
ache
achene
achievable
achieve
achievement
achiever
achoo
achromatic
achy
acid
acidic
acidify
acidity
acidly
acidosis
acidulous
acknowledge
acknowledged
acknowledgement
acknowledgment
acme
acne
acolyte
aconite
acorn
acoustic
acoustical
acoustically
acoustics
acquaint
acquaintance
acquaintanceship
acquainted
acquiesce
acquiescence
acquiescent
acquiescently
acquirable
acquire
acquirement
acquisition
acquisitive
acquisitively
acquisitiveness
acquit
acquittal
acre
acreage
acrid
acridity
acridly
acridness
acrimonious
acrimoniously
acrimoniousness
acrimony
acrobat
acrobatic
acrobatically
acrobatics
acronym
acrophobia
acropolis
across
across-the-board
acrostic
acrylic
act
acting
actinium
action
actionable
activate
activation
activator
active
actively
activeness
activism
activist
activity
actor
actress
actual
actuality
actualization
actualize
actually
actuarial
actuary
actuate
actuation
actuator
acuity
acumen
acupressure
acupuncture
acupuncturist
acute
acutely
acuteness
acyclovir
ad
adage
adagio
adamant
adamantly
adapt
adaptability
adaptable
adaptation
adapter
adaptive
adaptor
add
addable
addend
addenda
addendum
adder
addict
addicted
addiction
addictive
addition
additional
additionally
additive
addle
add-on
address
addressee
adduce
adenine
adenoid
adenoidal
adenoids
adept
adeptly
adeptness
adequacy
adequate
adequately
adequateness
adhere
adherence
adherent
adhesion
adhesive
adhesiveness
adieu
adieux
adios
adipose
adjacency
adjacent
adjacently
adjectival
adjectivally
adjective
adjoin
adjoining
adjourn
adjournment
adjudge
adjudicate
adjudication
adjudicative
adjudicator
adjudicatory
adjunct
adjuration
adjure
adjust
adjustable
adjuster
adjustment
adjustor
adjutant
ad-lib
adman
administer
administrate
administration
administrative
administratively
administrator
admirable
admirably
admiral
admiralty
admiration
admire
admirer
admiring
admiringly
admissibility
admissible
admissibly
admission
admissions
admit
admittance
admittedly
admix
admixture
admonish
admonishment
admonition
admonitory
ado
adobe
adolescence
adolescent
adopt
adoptable
adopted
adopter
adoption
adoptive
adorable
adorableness
adorably
adoration
adore
adorer
adoring
adoringly
adorn
adornment
adrenal
adrenalin
adrenaline
adrift
adroit
adroitly
adroitness
adsorb
adsorbent
adsorption
adulate
adulation
adulator
adulatory
adult
adulterant
adulterate
adulteration
adulterer
adulteress
adulterous
adultery
adulthood
adumbrate
adumbration
advance
advanced
advancement
advances
advantage
advantageous
advantageously
advent
adventitious
adventitiously
adventure
adventurer
adventuresome
adventuress
adventurous
adventurously
adventurousness
adverb
adverbial
adverbially
adversarial
adversary
adverse
adversely
adverseness
adversity
advert
advertise
advertisement
advertiser
advertising
advertorial
advice
advisability
advisable
advisably
advise
advised
advisedly
advisement
adviser
advisor
advisory
advocacy
advocate
adz
adze
aegis
aeon
aerate
aeration
aerator
aerial
aerialist
aerially
aerie
aerobatic
aerobatics
aerobic
aerobically
aerobics
aerodynamic
aerodynamically
aerodynamics
aeronautic
aeronautical
aeronautics
aerosol
aerospace
aesthete
aesthetic
aesthetically
aestheticism
aesthetics
afar
affability
affable
affably
affair
affairs
affect
affectation
affected
affectedly
affecting
affectingly
affection
affectionate
affectionately
afferent
affiance
affidavit
affiliate
affiliation
affinity
affirm
affirmation
affirmative
affirmatively
affix
afflatus
afflict
affliction
affluence
affluent
affluently
afford
affordable
afforest
afforestation
affray
affront
afghan
aficionado
afield
afire
aflame
afloat
aflutter
afoot
aforementioned
aforesaid
aforethought
afoul
afraid
afresh
aft
after
afterbirth
afterburner
aftercare
aftereffect
afterglow
afterimage
afterlife
afterlives
aftermarket
aftermath
afternoon
aftershave
aftershock
aftertaste
afterthought
afterward
afterwards
afterword
again
against
agape
agar
agar-agar
agate
agave
age
aged
ageism
ageist
ageless
agelessly
agelessness
agency
agenda
agent
age-old
ageratum
ages
agglomerate
agglomeration
agglutinate
agglutination
aggrandize
aggrandizement
aggravate
aggravated
aggravating
aggravatingly
aggravation
aggregate
aggregation
aggression
aggressive
aggressively
aggressiveness
aggressor
aggrieve
aggrieved
aghast
agile
agilely
agility
aging
agitate
agitated
agitation
agitator
agitprop
agleam
aglitter
aglow
agnostic
agnosticism
ago
agog
agonize
agonized
agonizing
agonizingly
agony
agoraphobia
agoraphobic
agrarian
agrarianism
agree
agreeable
agreeableness
agreeably
agreed
agreement
agribusiness
agricultural
agriculturalist
agriculturally
agriculture
agriculturist
agronomic
agronomist
agronomy
aground
ague
ah
aha
ahead
ahem
ahoy
aid
aide
aide-de-camp
aides-de-camp
aigrette
ail
aileron
ailing
ailment
aim
aimless
aimlessly
aimlessness
ain't
air
airbag
airbase
airborne
airbrush
air-condition
air-conditioned
air-conditioner
air-conditioning
air-cooled
aircraft
airdrop
airfare
airfield
airflow
airfoil
airfreight
airhead
airily
airiness
airing
airless
airlessness
airlift
airline
airliner
airlock
airmail
airman
airplane
airplay
airport
airs
airship
airsick
airsickness
airspace
airstrike
airstrip
airtight
airtime
air-to-air
airwaves
airway
airworthiness
airworthy
airy
aisle
ajar
akimbo
akin
alabaster
alack
alacrity
alarm
alarmed
alarming
alarmingly
alarmist
alas
alb
albacore
albatross
albeit
albinism
albino
album
albumen
albumin
albuminous
alchemist
alchemy
alcohol
alcoholic
alcoholically
alcoholism
alcove
alder
alderman
alderwoman
ale
aleatory
alehouse
alembic
alert
alertly
alertness
alewife
alewives
alfalfa
alfresco
alga
algae
algal
algebra
algebraic
algebraically
algorithm
algorithmic
alias
alibi
alien
alienable
alienate
alienated
alienation
alienist
alight
align
aligner
alignment
alike
aliment
alimentary
alimony
alit
alive
aliveness
aliyah
alkali
alkaline
alkalinity
alkalize
alkaloid
alkyd
all
all-around
allay
all-clear
allegation
allege
alleged
allegedly
allegiance
allegoric
allegorical
allegorically
allegorist
allegory
allegretto
allegro
allele
alleluia
allergen
allergenic
allergic
allergically
allergist
allergy
alleviate
alleviation
alley
alley-oop
alleyway
all-fired
alliance
allied
allies
alligator
all-important
all-inclusive
alliterate
alliteration
alliterative
alliteratively
all-night
all-nighter
allocate
allocation
allot
allotment
## my solution for all anagrams 
from time import clock
import os,sys

dictionary = 'list.txt'

takeout=' \t\'-+\n\r' ## deleted letters from words
## choosing first argument for translate
if sys.version[:3]>='2.6':
    table=None #python 2.6 or higher
else:
    print 'Old python'
    table=''
    for i in range(256): t+=chr(i)


def letters(a):
    let=''.join(sorted(a))
    let = let.translate(table,takeout)
    return let

def writeout(inp,out):
    words= [w.rstrip() for w in open(inp)]
    words=[letters(a)+' '+a for a in words]
    words.sort(key=len)
    open(out,'w').write('\n'.join(words))

def getanawords(aw='anawords.txt',al='analist.txt'):
    if not os.path.isfile(aw) and not os.path.isfile(al): writeout(inp=dictionary,out=al)
    
    anawords=dict()
    
    if not os.path.isfile(aw):
        for l,w in [j.split() for j in open(al)]:
            if l in anawords: anawords[l].append(w)
            else: anawords[l]=[w]
        print "Dict prepared in %1.3f s" % (clock()-t)

        f=open(aw,'w')
        for i in sorted(anawords,key=len):
            f.write(i+' '+' '.join(anawords[(i)])+'\n')
        print "Dict saved for future"
    else:
        for i in open(aw):
            i=i.rstrip().split()
            anawords[i[0]]=i[1:]
        print "Saved dict loaded"
    return anawords
 
if __name__=="__main__":
    ## listing all words
    t=clock()

    anawords=getanawords()
    print "Preparations took %1.3f s" % (clock()-t)
               
    print "To stop: enter empty line"
    while True:
        i=raw_input('Give word: ')
        t=clock()
        i=letters(i)
        if i :
            if i in anawords: print anawords[i]
            else: print 'Word is not in vocabulary'
            print '%i ms' % ((clock()-t)*1000)
        else: break

Specialties:
IT/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

1
Contributor
1
Reply
4
Views
7 Years
Discussion Span
Last Post by pyTony
0

Posted to anagrams part in rosettacode.
http://rosettacode.org/wiki/Anagrams#.7B.7Bheader.7CPython.7D.7D

Also improved previous version of Haskel algorithm version:

import urllib, itertools
from time import clock
words = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
t=clock()
anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)]
print('List preparation time: %.3f ms' % ((clock()-t)*1000))
t=clock()
topten= sorted(anagrams, key=len)[-10:]
count = len(topten[-1]) ## last in sorted list is longest
print '\n'.join([', '.join(ana) for ana in topten if len(ana) == count])
print('Longest finding time: %.3f ms' % ((clock()-t)*1000))
input('Ready')
"""List preparation time: 459.000 ms
abel, able, bale, bela, elba
caret, carte, cater, crate, trace
angel, angle, galen, glean, lange
alger, glare, lager, large, regal
elan, lane, lean, lena, neal
evil, levi, live, veil, vile
Longest finding time: 18.745 ms
Ready
"""

Edited by pyTony: n/a

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.