Re: Alphabetizing?

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

  1. Lee Harr

    Lee Harr Guest

    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!
    >
    >



    How about just sort()ing them?

    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
    #1
    1. Advertising

  2. 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
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jawdoc
    Replies:
    2
    Views:
    262
    jawdoc
    Mar 9, 2008
  2. jawdoc
    Replies:
    1
    Views:
    632
    Daniel T.
    Mar 10, 2008
  3. Zenki Nine

    Alphabetizing

    Zenki Nine, Jan 23, 2008, in forum: Ruby
    Replies:
    11
    Views:
    212
    Todd Benson
    Jan 26, 2008
Loading...

Share This Page