Re: Alphabetizing?

Discussion in 'Python' started by Lee Harr, Aug 24, 2003.

1. Lee HarrGuest

In article <> wrote:
> Ok, im trying to creat a small simple program that alphabetizes user
> inputed words. I thought why not just create a def that splits all the
> words down into char's then take the first char and crosscheck it with all
> lowercase letters. Then find its position and return the results to the
> user in order or 1-26! But this takes a long time and the code gets
> confusing. Any suggestion? Thanx in advance!
>
>

You can define a custom sort function if you want an
alphabetical rather than lexical sort. ie:

words = []
while 1:
word = raw_input('enter word ("done" to finish) :')
if word == 'done':
break
words.append(word)

def sort_alpha(a, b):
if a.lower() < b.lower():
return -1
elif a.lower() > b.lower():
return 1
else:
return 0

words.sort(sort_alpha)

print words

Lee Harr, Aug 24, 2003

2. Erik Max FrancisGuest

Lee Harr wrote:

> How about just sort()ing them?
>
> You can define a custom sort function if you want an
> alphabetical rather than lexical sort. ie:

...
> def sort_alpha(a, b):
> if a.lower() < b.lower():
> return -1
> elif a.lower() > b.lower():
> return 1
> else:
> return 0
>
> words.sort(sort_alpha)

You've got the right approach (sorting based on a signature derived from
the string, rather than the string itself), although to be picky this
isn't yet an alphabetic sort, since it should be stripping away
non-alphabetic characters:

>>> sort_alpha("where's", "whereas")

-1

Of course this starts to get into questions of what you consider a word
or not, but a true alphabetic sort would remove non-alphabetic
characters first. You can do this easily enough with string.maketrans
and S.translate.

--
Erik Max Francis && && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ An undevout astronomer is mad.
\__/ Edward Young

Erik Max Francis, Aug 25, 2003