Syrint
Syrint

Reputation: 29

Find if a String is in Ascending order (Lexicographically)

I have a problem where I need to read an unknown amount of lines from a text file, and determine whether or not the lines are in ascending order. Any help would be much appreciated.

Upvotes: 0

Views: 1644

Answers (1)

Zach Gates
Zach Gates

Reputation: 4130

If your file looks something like this:

alphabet
bee
house
part
wine

And you want to check if the lines are in lexicographic order, you can use something simple like this:

lines = open("myfile.txt", "r").read().splitlines()
if sorted(lines) == lines:
    print("File is in the correct order.")

All this does is open the file, separates it into individual lines, and compares the lexicographical order to the actual order. You can do this because Python sorts lexicographically, as seen here:

tuples [and lists] are compared lexicographically

Upvotes: 2

Related Questions