On Tue, Aug 25, 2009 at 2:14 PM, kreglet <kreg...@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
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor