Python - arranging words in alphabetical order

73,786

Solution 1

Python's string comparisons are lexical by default, so you should be able to call max and get away with it:

In [15]: sentence
Out[15]: ['this', 'is', 'a', 'sentence']
In [16]: max(sentence)
Out[16]: 'this'

Of course, if you want to do this manually:

In [16]: sentence
Out[16]: ['this', 'is', 'a', 'sentence']

In [17]: answer = ''

In [18]: for word in sentence:
   ....:     if word > answer:
   ....:         answer = word
   ....:         

In [19]: print answer
this

Or you can sort your sentence:

In [20]: sentence
Out[20]: ['this', 'is', 'a', 'sentence']

In [21]: sorted(sentence)[-1]
Out[21]: 'this'

Or, sort it reversed:

In [25]: sentence
Out[25]: ['this', 'is', 'a', 'sentence']

In [26]: sorted(sentence, reverse=True)[0]
Out[26]: 'this'

But if you want to fully manual (which is so painful):

def compare(s1, s2):
    for i,j in zip(s1, s2):
        if ord(i)<ord(j):
            return -1
        elif ord(i)>ord(j):
            return 1
    if len(s1)<len(s2):
        return -1
    elif len(s1)>len(s2):
        return 1
    else return 0

answer = sentence[0]
for word in sentence[1:]:
    if compare(answer, word) == -1:
        answer = word

# answer now contains the biggest word in your sentence

If you want this to be agnostic of capitalization, be sure to call str.lower() on your words first:

sentence = [word.lower() for word in sentence] # do this before running any of the above algorithms

Solution 2

Use the sort() method.

strings = ['c', 'b', 'a']
strings.sort()
print strings

Output will be,

['a', 'b', 'c']

In case you want the last, you can use the max() method.

Solution 3

As noted in a previous answer, string comparisons are lexical by default, so min() and max() can be used. To handle both upper- and lower-cased words, one can specify key=str.lower. For example:

s=['This', 'used', 'to', 'be', 'a', 'Whopping', 'Great', 'sentence']
print min(s), min(s, key=str.lower)
# Great a

print max(s), max(s, key=str.lower)
# used Whopping

Solution 4

If you have a mix of capitalized words and lowercase words you could do this:

from string import capwords     

words = ['bear', 'Apple', 'Zebra','horse']

words.sort(key = lambda k : k.lower())

answer = words[-1]

Result:

>>> answer
'Zebra'
>>> words
['Apple', 'bear', 'horse', 'Zebra']

Solution 5

This would be how I would do it.

  1. Define the string: For arguments sake let us say that the string is already predefined.

    sentence = "This is the sentence that I need sorted"
    
  2. Use the split() method: The split() method returns a list of "words" from the sentence string. I use the term "word" here loosely as the method has no conception of "word", it merely separates the sentence string into a list by parsing it for characters delimited by whitespace and outputs these characters as discrete items in a list. This list is not yet alphabetically ordered.

    split_sentence = sentence.split()
    
  3. Use the sorted function: The sorted function returns an alphabetically ordered version of the split_sentence list.

     sorted_sentence = sorted(split_sentence)
    
  4. Print the last element in the list:

    print(sorted_sentence[-1])
    
Share:
73,786
Admin
Author by

Admin

Updated on July 11, 2022

Comments

  • Admin
    Admin almost 2 years

    The program must print the name which is alphabetically the last one out of 8 elements. The names/words can be inputted in any way through code. I think I should be using lists and in range() here. I had an idea of comparing the first/second/third/... letter of the input name with the letters of the previous one and then putting it at the end of the list or in front of the previous one (depending on the comparison), and then repeating that for the next name. At the end the program would print the last member of the list.

  • abarnert
    abarnert over 11 years
    Why would you use string.capwords(s) instead of just s.lower() or s.upper()?
  • Akavall
    Akavall over 11 years
    @abarnert, no real reason. I see that advantage of s.lower() and s.upper() is that you do not need import any module (string), do you know any other advantages?
  • abarnert
    abarnert over 11 years
    Well, comparing s.lower() is the paradigmatic way to do case-insensitive (ASCII) comparisons; using a function that's so little-known that they chose not to add it as a str method means that people will have to think about the code instead of immediately recognizing what it does (and automated refactoring tools won't recognize it at all). You've heard of "TOOWTDI", right? There are also minor advantages—lower is also more likely to be optimized on different Python implementations, it's easier to read (one word that tells you what it does instead of two, one of which is irrelevant), etc.
  • abarnert
    abarnert over 11 years
    +1. Out of all of the answers, this is the most concise, and it directly answers the OP's question and explains why it works. However, you might want to add some mention of locale.collate if you want to handle mixed-case words with non-ASCII letters.