2009/1/19 John Fouhy <j...@fouhy.net> > 2009/1/20 Emad Nawfal (عماد نوفل) <emadnaw...@gmail.com>: > Of course, this is not necessarily the best answer for your particular > problem. The problem with sorting is that you have to look at some > elements more than once. For short lists, it's not a problem, but it > can slow you down on bigger lists. You could also find the shortest > element by going through the list, remembering the shortest element > you've seen so far. This will be quicker if you only want to find the > single shortest. >
Here's the first thing that came to mind: > from sys import maxint > > def MinMax(Sentence=""): > minLen = maxint > maxLen = 0 > > for word in Sentence.split(): > if len(word) > maxLen: > maxWord = word > maxLen = len(word) > if len(word) < minLen: > minWord = word > minLen = len(word) > return minLen, minWord, maxLen, maxWord > > > print MinMax("No victim has ever been more repressed and alienated than the > truth") > Using sys.maxint to prime minLen is overkill, of course - "antidisestablishmentarianism" is only 28 letters long, after all - but it should be larger than any word you can expect to see. This doesn't catch ties, though... could do that like so: for word in Sentence.split(): > if len(word) == minLen: > minWord.append(word) > if len(word) == maxLen: > maxWord.append(word) > if len(word) > maxLen: > maxWord = [word] > maxLen = len(word) > if len(word) < minLen: > minWord = [word] > minLen = len(word) > > -- www.fsrtechnologies.com
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor