[Tutor] Algorithm

Wayne srilyk at gmail.com
Mon Aug 24 13:19:35 CEST 2009


On Sun, Aug 23, 2009 at 10:01 PM, kreglet <kreglet at gmail.com> wrote:

>
> Alan,
>
>  Thanks for the reply. This is not homework, it is a hobby. I am 44 years
> old. I was using Visual Basic, but recently decided to switch to Linux and
> have no intentions of going back to windows. Python seems like a good
> computer language. I read somewhere the the best way to learn it was to
> pick
> a project and start programming. Since one of my other hobbies is word
> games
> and Linux is severely lacking in this area I decided to write a game
> similar
> to Text Twist in windows for my first project.
>
>  The game I am writing has a graphical front end using GTK and the code so
> far is long and in more than one file (to keep the gui code seperate). I
> will gladly email you the whole thing to you if you like.
>
>  In my research, I looked at examples of permutations, lists, sets, and
> most recently dictionaries which I have the feeling is the solution.
> Permutation looked good, but I am an amateur programer and couldn't quite
> grasp the concepts from the examples I found. Dictionaries hold promise as
> it can be used to get a count of the letters in words.
>
> from operator import itemgetter
>
> def countletters(word):
>        lettercount = {}
>        for letter in word:
>                lettercount[letter] =lettercount.get(letter,0) + 1
>        print sorted(lettercount.iteritems(), key=itemgetter(1))
>
>
> countletters("batty")
> [('a', 1), ('y', 1), ('b', 1), ('t', 2)]
>
> countletters("bat")
> [('a', 1), ('b', 1), ('t', 1)]
>
> countletters("bats")
> [('a', 1), ('b', 1), ('s', 1), ('t', 1)]
>
> bat is in batty. bats is not.
>
> I have a list of words in wordlist.txt. I can write a loop the do the
> letter
> counts for each word, but I can't figure out how to compare them.


I would actually not bother sorting your return from countletters - keep it
a dictionary.

Then you can compare like this:

mainword = countletters('batty')
cmpword = countletters('bat')

def myfunc(cmpword, mainword):
  for letter in cmpword:
    if mainword.gets(letter):
        if cmpword[letter] >mainword[letter]:
             return False
    else:
        return False

I think that should work. First you're looping over each letter in cmpword.
Because mainword is also a dictionary the order isn't terribly important.
Then you check if the letter is in mainword. If it's not, obviously cmpword
isn't in mainword, so return False. If the letter is, compare the counts. If
cmpword has more letters than mainword, it's not in the word so again return
False.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090824/84cc7809/attachment.htm>


More information about the Tutor mailing list