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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Use the
sort()
method.Output will be,
In case you want the last, you can use the
max()
method.This would be how I would do it.
Define the string: For arguments sake let us say that the string is already predefined.
Use the
split()
method: Thesplit()
method returns a list of "words" from thesentence
string. I use the term "word" here loosely as the method has no conception of "word", it merely separates thesentence
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.Use the
sorted
function: The sorted function returns an alphabetically ordered version of thesplit_sentence
list.Print the last element in the list:
Just use the following:
In python the method sort() sorts all strings alphabetically so you can use that function.
You can make a list of all your words and then :
This would result a alphabetically sorted list.
Python's string comparisons are lexical by default, so you should be able to call
max
and get away with it:Of course, if you want to do this manually:
Or you can sort your sentence:
Or, sort it reversed:
But if you want to fully manual (which is so painful):
If you want this to be agnostic of capitalization, be sure to call
str.lower()
on yourword
s first:As noted in a previous answer, string comparisons are lexical by default, so
min()
andmax()
can be used. To handle both upper- and lower-cased words, one can specifykey=str.lower
. For example: