Hey guys I finally got my word unscrambler working the other day, now I fire it up with same code same everything and for some reason getting double output from a list that shouldn't be. So if someone could either look this over and find a problem or maybe do a test run on their computer and let me know if something is currupt somehow on my system that would be great to. I just can't tell if its the code or my computer or the interprater that is messed up. I'll attach some sample files to use to run it. Thanks again.

Here is the code.

#decode scrambled word from a word list in 30 sec or less.
wordlist = []
possible = []
matches = []
thelist = []
myvar = -1
c = -1
p = -1
wordlistfile = open('C:\\Documents and Settings\\William\\Desktop\\wordlist\\wordlist.txt', 'r')
possiblefile = open('C:\\Documents and Settings\\William\\Desktop\\possible.txt', 'r')
#add file contents to lists.
while p < 9:
    i = -1
    p = p + 1
    print p
    for line in wordlistfile:
        wordlist.append(line.strip())
    for line in possiblefile:
        possible.append(line.strip())
#match length of words to narrow possible matches
    for line in wordlist:
        i = i + 1
        if len(wordlist[i]) == len(possible[p]):
            matches.append(wordlist[i])
#narrow further by checking for instances of charecters
    word = possible[p]
    x = len(matches)
    while c < x:
        c = c + 1
        for letter in word:
            if c == x:
                break
            if not letter in matches[c]:
                del matches[c]
                x = x - 1
#start rearanging word.
    word = word.strip().lower()
    for pos in matches:
        tmp1 = []
        tmp2 = []
        tmp1 = list(pos.lower().strip())
        tmp2 = list(word)
        tmp1.sort()
        tmp2.sort()
        if tmp1 == tmp2:
            print p
            myvar = myvar + 1
            thelist.append(pos)
            if myvar == 10:
                print(thelist[myvar])
                break
            elif myvar < 9:
                print(thelist[myvar] + ', ')

wordlistfile.close()
possiblefile.close()
Attachments
raolns
1itdalig
caeaph
eeirgg
nanajo
ahtrru
sunatr
cc0171n
rfisedn
aangle
html:)
121212
131313
123123
654321
8675309
666666
696969
888888
1234567
21122112
12345678
asdfjkl;
hal9000
bond007
ncc1701d
ncc1701e
ncc1701
thx1138
a12345
abcd1234
1234qwer
1a2b3c
1q2w3e
test123
1p2o3i
puppy123
kitten12
qwerty12
john316
apollo13
ne1469
amanda1
mazda1
angela1
alpha1
sarah1
nirvana1
bubba1
scuba1
rambo1
charlie1
david1
digital1
dragon1
honda1
shadow1
eagle1
freak1
james1
1sanjose
apple1
master1
happy1
martin1
jason1
larry1
number1
robert1
soccer1
direct1
chester1
welcome1
french1
hockey1
chevy1
scooter1
chris1
lucky1
teddy1
phoenix1
hello1
julie1
kevin1
pookie1
viper1
jenny1
jesus1
kelly1
money1
mouse1
sting1
justin1
molly1
sunny1
front242
jordan23
2welcome
h2opolo
bird33
4runner
babylon5
star69
ib6ub9
america7
seven7
number9
porsche9
barbara
database
banana
bananas
canada
jamaica
amanda
valhalla
samantha
yamaha
natasha
alaska
tamara
zapata
avatar
basketba
baseball
basebal
bastard
nebraska
banane
abigail
sabrina
batman
cocacola
cascade
cardinal
claudia
packard
cannonda
apache
america
canela
camera
caesar
warcraft
catalog
chapman
zachary
alicia
patricia
carolina
nicarao
captain
nautica
pascal
rascal
camaro
nascar
deadhead
adidas
alexande
airhead
alexandr
andrea
gandalf
grandma
happyday
indiana
paladin
miranda
adrian
dakota
dallas
mayday
pandora
sandra
xanadu
angela
margaret
stargate
savage
gateway
athena
ariane
pearljam
maryjane
oatmeal
pamela
pantera
vanessa
graymail
iguana
jaguar
galaxy
gasman
hannah
hawaii
mariah
jonathan
marshal
martha
nathan
italia
aikman
saskia
vanilla
mailman
animal
animals
impala
attila
marina
mariposa
nirvana
arizona
joanna
january
lakota
avalon
alyssa
yomama
montana
mantra
tazman
tarzan
starwars
bobcat
badboy
barbie
babies
basketb
rabbit
bamboo
rebecca
abcdef
abcdefg
blackie
excalibu
campbell
tacobell
bigmac
jsbach
columbia
buddha
badger
butthead
bradley
brenda
bernard
ladybug
diablo
blizzard
brandi
bandit
brandon
brandy
beagle
isabelle
elizabet
beanie
beatles
webmaste
beaner
beaver
fireball
beautifu
gabriell
gabriel
poohbear
bertha
benjamin
bailey
beavis
basket
blaster
albert
blazer
barney
strawber
braves
buffalo
football
softball
footbal
foobar
bigman
gambit
global
malibu
library
brasil
brazil
rainbow
obiwan
kombat
snowball
marlboro
snowbal
playboy
absolut
wombat
canced
icecream
chance
celica
cracker
cancer
access
pacific
chicago
chocolat
arctic
clancy
cactus
dickhead
maddock
medical
claude
sundance
dancer
crawford
richard
wildcat
picard
colorado
conrad
corrado
changeme
chelsea
peaches
research
teachers
teacher
creative
cleaner
france
challeng
michael
charlie
archie
hacker
chanel
rachel
charles
patches
jackie
janice
jessica
maverick
metallic
caroline
special
claire
iceman
maurice
maveric
veronica
carrie
cassie
active
slacker
packer
packers
marcel
coltrane
carole
lacrosse
scarlet
scarlett
castle
carmen
pacers
racerx
stacey
catfish
californ
francois
francis
falcon
graphic
logical
garlic
camping
racing
cougars
cougar
chiquita
christia
nicholas
champion
cynthia
charity
charlott
champs
caitlin
victoria
tricia
patrick
calvin
monica
macintos
action
picasso
jackson
malcolm
coolman
classroo
carlos
crystal
compaq
tomcat
marcus
cannon
corona
cyrano
topcat
tractor
laddie
undead
edward
maddog
diamond
donald
woodland
greenday
danielle
dreamer
reader
garfield
alfred
reading
gerald
garden
shithead
daniel
ireland
raider
raiders
daytek
leonard
dreams
anderson
darren
sanders
andrew
retard
tuesday
asdfghjk
asdfgh
dragonfl
florida
friday
asdfjkl
digital
godzilla
douglas
dragon
harold
rhonda
zaphod
howard
shadows
shadow
thursday
indian
island
lindsay
lizard
madison
pyramid
darwin
tardis
wizard
majordom
jordan
dollars
orlando
portland
ronald
rodman
raymond
monday
sunday
password
passwd
jeanette
sweetpea
jaeger
general
eagles
heather
kathleen
hawkeye
elephant
sheena
theresa
theatre
whatever
whateve
amelie
melanie
elaine
valerie
jeanne
yankees
walleye
please
seattle
weasel
awesome
netware
teresa
grateful
frankie
fireman
ferrari
farmer
safety
maggie
georgia
aggies
imagine
galileo
goalie
enigma
mirage
wrangler
angels
german
orange
oranges
ranger
garnet
voyager
garrett
target
health
katherin
sheila
stephani
sapphire
asshole
harley
stealth
whales
ashley
hammer
herman
theman
hamster
matthew
panther
hearts
harvey
jasmine
mikael
mailer
melissa
valentin
lorraine
alpine
aliens
tequila
reality
laurie
alexis
sammie
maxime
marine
vampire
insane
painter
petunia
praise
pirate
sierra
asterix
xavier
jasper
lakers
walker
kramer
market
tanker
wanker
parker
startrek
skater
maxwell
stella
montreal
temporal
sampler
marley
samuel
napoleon
espanol
snapple
planet
lauren
stanley
apples
players
player
raquel
slayer
travel
walter
lestat
superman
masters
master
tanner
suzanne
newpass
peanut
warren
tiffany
wolfgang
flamingo
farming
fugazi
franklin
family
fountain
wolfman
smashing
virginia
sailing
training
stingray
giants
guitar
magnum
morgan
mustang
gymnast
august
mishka
harrison
spanish
shanti
joshua
kathryn
shalom
hansolo
phantom
thomas
shannon
hanson
anthony
sharon
hatton
author
arthur
nikita
williams
william
raistlin
olivia
julian
jasmin
allison
marilyn
alison
polaris
sailor
quality
sylvia
ironman
mountain
tinman
marino
martin
marvin
matrix
nissan
passion
station
tristan
austin
utopia
warriors
warrior
artist
travis
krystal
spanky
sparky
apollo
salmon
psalms
larson
royals
taylor
norman
snowman
sampson
samson
mozart
watson
saturn
tattoo
toyota
sparrow
parrot
passwor
qwaszx
stuart
taurus
bubbles
debbie
bluebird
bigbird
pebbles
robbie
hobbit
jimbob
booboo
december
quebec
robotech
republic
october
public
zxcvbnm
broncos
cowboys
scooby
cowboy
firebird
bigred
bridges
dogbert
thunderb
birdie
blondie
dilbert
doobie
blonde
rosebud
bigdog
bulldog
sunbird
remember
septembe
homebrew
herbert
biteme
bernie
reebok
rebels
byteme
brewster
webster
boogie
junebug
goblue
goober
shelby
theboss
kimberly
zombie
timber
bonnie
benoit
business
nesbitt
bootsie
bluesky
brooke
volleyb
bullet
blowme
trouble
butler
boomer
benson
booster
trebor
buster
bigfoot
blowfish
bright
bowling
biology
gibson
bullshit
robinhoo
bookit
wilbur
bonjour
symbol
boston
browns
buttons
button
brutus
cccccc
electric
science
chicken
cricket
celtics
cyclone
connect
concept
soccer
success
church
chucky
scotch
cloclo
cuddles
depeche
mercedes
frederic
deutsch
duckie
wicked
cinder
director
orchid
dominic
doctor
cheese
coffee
fletcher
gretchen
college
michelle
michele
speech
chester
celine
eclipse
pierce
service
colleen
telecom
welcome
spencer
center
except
secret
chiefs
fletch
fuckme
fucker
michell
mitchell
michel
chipper
hockey
cheryl
techno
porsche
hector
cherry
justice
pickle
mickey
snicker
snickers
cookie
cookies
nicole
police
clipper
mexico
connie
vincent
prince
princess
picture
pisces
security
cruise
rocket
puckett
tucker
clover
computer
compute
mercury
newcourt
courtney
cooper
scooter
coyote
copper
fuckoff
scruffy
fiction
fuckyou
gocougs
christin
christop
chrissy
christ
christy
school
psycho
politics
knicks
lincoln
unicorn
scorpion
corwin
sonics
scorpio
victor
victory
curtis
trucks
control
compton
moocow
cosmos
popcorn
xcountry
country
scotty
deedee
dundee
freddy
dodger
dodgers
defense
freedom
fender
legend
deliver
denise
kennedy
ledzep
denver
speedo
speedy
dexter
friend
friends
doggie
digger
goldie
redwing
design
doogie
dougie
golden
hendrix
thunder
inside
kinder
redskin
dookie
lindsey
dennis
trident
sendit
sidney
detroit
spider
strider
donkey
reynolds
elwood
redrum
wonder
notused
student
sydney
windsurf
oxford
midnight
dwight
hotdog
indigo
kingdom
snoopdog
gordon
phurivdli
judith
dolphin
dolphins
hotrod
dorothy
midori
skidoo
domino
nimrod
wisdom
windows
dustin
stupid
drizzt
london
studly
voodoo
peewee
reefer
eugene
sweetie
kleenex
skeeter
penelope
steelers
steele
eeyore
weezer
jeffrey
jennifer
jenifer
ferret
reggie
george
wheeling
genesis
sergei
energy
hershey
kenneth
shelley
helpme
wheels
promethe
hermes
stephen
einstein
jessie
nellie
leslie
letmein
zeppelin
etoile
nemesis
internet
pierre
jewels
jeremy
jensen
jester
kelsey
loveme
people
explorer
wrestle
letter
wesley
velvet
western
newuser
steven
popeye
europe
pepper
express
tester
stever
testtest
sweets
sweety
tweety
griffey
golfer
fisher
spitfire
flipper
xfiles
fozzie
sunflowe
flowers
flower
flyers
forest
surfer
future
ginger
tigger
google
nugget
gregory
theking
gopher
gemini
gilles
piglet
penguin
guinness
singer
testing
genius
tigers
gretzky
gunner
nguyen
grover
shirley
memphis
sunshine
phoenix
whitney
zenith
hootie
sophie
joseph
huskers
shelly
mother
thumper
hornets
hornet
hunter
shooter
topher
horses
zephyr
sherry
millie
willie
olivier
minnie
winnie
trixie
jupiter
killme
killer
mookie
kermit
kristen
tinker
kittens
kitten
pookie
skipper
miller
soleil
elliot
little
merlin
simple
smiles
smiley
online
wolverin
liverpoo
iloveyou
oliver
louise
violet
silver
sylvie
mortimer
swimmer
emmitt
monique
pentium
mittens
niners
intern
winner
tennis
senior
sniper
sunrise
winter
tootsie
puppies
ripper
sprite
monkey
smokey
network
newyork
volley
yellow
russell
lennon
nelson
looney
loveyou
protel
wolves
purple
russel
turtle
memory
summer
monster
vermont
trumpet
system
newton
yvonne
runner
preston
entrop

On first blush, you need to create your wordlist outside the loop, or you will keep appending to it all the time:

#decode scrambled word from a word list in 30 sec or less.
matches = []
thelist = []
myvar = -1
c = -1
p = -1
wordlistfile = open('C:\\Documents and Settings\\William\\Desktop\\wordlist\\wordlist.txt', 'r')
possiblefile = open('C:\\Documents and Settings\\William\\Desktop\\possible.txt', 'r')
#add file contents to lists.
wordlist = []
possible = []
for line in wordlistfile:
    wordlist.append(line.strip())
for line in possiblefile:
    possible.append(line.strip())

while p < 9:
    i = -1
    p = p + 1
    print p
    for line in wordlistfile:
        wordlist.append(line.strip())
    for line in possiblefile:
        possible.append(line.strip())
#match length of words to narrow possible matches
    for line in wordlist:
        i = i + 1
        if len(wordlist[i]) == len(possible[p]):
            matches.append(wordlist[i])
#narrow further by checking for instances of charecters
    word = possible[p]
    x = len(matches)
    while c < x:
        c = c + 1
        for letter in word:
            if c == x:
                break
            if not letter in matches[c]:
                del matches[c]
                x = x - 1
#start rearanging word.
    word = word.strip().lower()
    for pos in matches:
        tmp1 = []
        tmp2 = []
        tmp1 = list(pos.lower().strip())
        tmp2 = list(word)
        tmp1.sort()
        tmp2.sort()
        if tmp1 == tmp2:
            print p
            myvar = myvar + 1
            thelist.append(pos)
            if myvar == 10:
                print(thelist[myvar])
                break
            elif myvar < 9:
                print(thelist[myvar] + ', ')

wordlistfile.close()
possiblefile.close()

O.K. got that and seems reasonable enough, but still getting this output from my p variable first call from before goes into the lists secound after the output of the lists.

0
0
larson, 
1
1
digital1, 
2
2
apache, 
3
3
reggie, 
3
reggie, 
4
4
joanna, 
5
5
arthur, 
6
6
saturn, 
7
7
ncc1701, 
8
8
9
9
angela

As you can see when it gets to reggie for some reason there is one extra ouput which throws the whole thing out of whack!!! It really shouldn't do that but still is.

There are two "print p" in your code.

Sorry, I left the original

for line in wordlistfile:
    wordlist.append(line.strip())
for line in possiblefile:
    possible.append(line.strip())

still in the loop. Just remove it. On first blush meant that I didn't test it out, just looked at your code.

Why it doesn't print out 'friends', I don't know.

Yeah I did remove the appends from the loop and that output I posted is just showing that the lists seem to be giving a double output on item 3 reggie thus screwing the indexing up tward the bottom of the code, but it shouldn't be the way its coded. Line 13 in the output should never happen, and I think that is why the rest of it don't work right either. If anyone can tell me why it is happening or come up with some type of coding to stop it from doing that would be very helpful.

By using set() you can really streamline your code:

# modified to allow testing
wordlistfile = open('wordlist.txt', 'r')
possiblefile = open('possible.txt', 'r')

# add file contents to lists
wordlist = []
possible = []
for line in wordlistfile:
    wordlist.append(line.strip())
for line in possiblefile:
    possible.append(line.strip())

match_list = []
for poss in possible:
    for word in wordlist:
        # narrow down the wordlist with len() and set()
        if len(poss) == len(word):
            if set(poss) == set(word):
                # now partial match the characters
                count = 0
                for c in poss:
                    if c in word:
                        count += 1
                if count == len(poss):
                    match_list.append((poss, word))

# show result
print "there are %d matches:" % len(match_list)
for match in match_list:
    print "%-10s -->  %-10s" % (match)

"""
my result -->
there are 10 matches:
raolns     -->  larson
1itdalig   -->  digital1
caeaph     -->  apache
eeirgg     -->  reggie
nanajo     -->  joanna
ahtrru     -->  arthur
sunatr     -->  saturn
cc0171n    -->  ncc1701
rfisedn    -->  friends
aangle     -->  angela
"""

A faster way

wordlistfile = open('wordlist.txt', 'r')
possiblefile = open('possible.txt', 'r')

D = {}
for line in wordlistfile:
  word = line.strip()
  s = "".join(sorted(word))
  if not s in D:
    D[s] = []
  D[s].append(word)

for line in possiblefile:
  scrambled = line.strip()
  s = "".join(sorted(scrambled))
  if s in D:
    print scrambled, sorted(D[s])

:)

Thanks for pointing out the set module I just did some research on it and its great. Seems strange to me though that sort was acting the way it was, although I notice by looking at your code I need to work on my grammer as I put it in another post. I'm workin on it!!! Anyways I think I'll modify the program to use set instead of sort for now, but I wanna find out why sort not working correctly, so I know how to use it in the future. Oh and thanks for the hint on appending the lists to Gribouillis.

You want it real sweet and short?

# add file contents to lists
wordlist = [line.strip() for line in file('wordlist.txt')]
possible = [line.strip() for line in file('possible.txt')]

match_list = []
for poss in possible:
    for word in wordlist:
        # narrow down the wordlist with len() and set()
        if len(poss) == len(word) and set(poss) == set(word):
                match_list.append((poss, word))

# show result
print "there are %d matches:" % len(match_list)
for match in match_list:
    print "%-10s -->  %-10s" % (match)

Pulling all the tricks of Python, but harder to read and understand:

for poss in [line.strip() for line in file('possible.txt')]:
    for word in [line.strip() for line in file('wordlist.txt')]:
        if len(poss) == len(word) and set(poss) == set(word):
                print "%-10s -->  %-10s" % (poss, word)

ZZucker could you explain to me where or how the variables like %d are getting there information from I have never used that type of variable before.

O.K. I'm understanding that it is used to convert between types, but what is the -10 in %-10s for? Wouldn't you only need to do %s?

O.K that makes a lot more sense now, so the -10 is a flag you can set. Didn't quite catch that at first, thanks for the links to that information.

print "%-10s --> %-10s" % (poss, word)
"%-10s --> %-10s" is a formatting string where %s is a place holder for a string and %-10s means put the string into a 10 space field left adjusted. Conversely %d is a placeholder for an integer and %10.3f would be a placeholder for a float number putting it into a 10 space field with 3 decimals showing.

Look under % formatting in the manual. It works similar to the C language printf().

This question has already been answered. Start a new discussion instead.