[Tutor] Algorithm

Kent Johnson kent37 at tds.net
Wed Aug 26 05:02:20 CEST 2009


On Tue, Aug 25, 2009 at 9:55 PM, Wayne<srilyk at gmail.com> wrote:
> I just did a quick test and this code seems to work correctly:
> def countletters(word):
>     lettercount = {}
>     for letter in word:
>         lettercount[letter] = lettercount.get(letter, 0) + 1
>     return lettercount
> def comparewords(cmpword, mainword):
>     for letter in cmpword:
>         if mainword.get(letter):
>             if cmpword[letter] > mainword[letter]:
>                 return False

This could be
  if cmpword[letter] > mainword.get(letter, 0):

The whole loop could be simplified a bit using dict.items():
for letter, count in cmpword.items():
  if count > mainword.get(letter, 0):
    return False

Kent


More information about the Tutor mailing list