Search code examples
pythonlexicographic

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.


Solution

  • 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