[Tutor] Algorithm
Wayne
srilyk at gmail.com
Wed Aug 26 03:55:56 CEST 2009
On Tue, Aug 25, 2009 at 2:14 PM, kreglet <kreglet at gmail.com> wrote:
>
> Wayne,
> I appreciate your patience with me. I still can't get this to work:
>
>
> from operator import itemgetter
> class testwords:
> def __init__(self):
> self.lettercount={}
> self.inword=False
> self.mainword=""
> self.cmpword=""
>
> def countletters(word):
> lc.lettercount = {}
> for letter in word:
> lc.lettercount[letter] =lc.lettercount.get(letter,0) + 1
> print sorted(lc.lettercount.iteritems(), key=itemgetter(1))
>
> def comparewords(cmpword, mainword):
> for letter in cmpword:
> if mainword.get(letter):
> print letter, cmpword[letter], mainword[letter]
> if cmpword[letter] >mainword[letter]:
> lc.inword=False
>
> else:
> if cmpword[letter] <=mainword[letter]:
> lc.inword=True
>
>
> lc=testwords()
>
> lc.mainword="batty"
> lc.cmpword="bat"
>
> countletters(lc.mainword)
> mainword = lc.lettercount
>
> countletters(lc.cmpword)
> cmpword = lc.lettercount
>
> comparewords(cmpword, mainword)
>
> if lc.inword==True:
> print lc.cmpword + " IS in: " + lc.mainword
> if lc.inword==False:
> print lc.cmpword + " IS NOT in: " + lc.mainword
This is a bit redundant - since lc.inword returns True or False you can
simply test:
if lc.inword:
#do stuff
else:
#do other stuff
That's really the proper way to do it. Also, AFAIK two "if" statements take
longer than an if/else statement. Of course we're talking about ms or less,
but it still reads better to have an if/else.
It appears that I've not been coding enough lately - and my explanation has
been a bit of a failure.
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
else:
return False
return True
word1 = countletters('python')
word2 = countletters('pyz')
print comparewords(word2, word1)
at least "py" was in "python", so was "pyn", but 'pyz' was not.
HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090825/57b63ddd/attachment.htm>
More information about the Tutor
mailing list