1

I have a text file that contains:

I like potatoes
Potatoes are good
Potatoes contain starch

And I want to test if each sentence is in lexicographical order.

If the sentence is I would like it to output "This is in lexicographic order"

I'm not too sure what to do.

UdonSenpai
  • 55
  • 1
  • 6

1 Answers1

0

One way would be to read in the file, split the lines, put the lines into order, then check to see whether the order is the same or different.

This might not be the most efficient way but would work:

with open('potatoes.txt') as potatoes:
    potato_lines = potatoes.readlines()

print sorted(potato_lines) == potato_lines

Answers to this question show you how to check without sorting.

e.g, this answer gives a neat way of generating pairs to check order:

from itertools import tee, izip

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

def is_sorted(iterable, key=lambda a, b: a <= b):
    return all(key(a, b) for a, b in pairwise(iterable))

Which you could then use:

with open('potatoes.txt') as potatoes:
    print is_sorted(potatoes)
Community
  • 1
  • 1
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • How would I separate each line so each individual sentence has an output? – UdonSenpai Aug 08 '15 at 23:03
  • @UdonSenpai That's a different question. By commenting here you're only asking me, not the whole of stackoverflow. You need to show some code, and be far clearer in your questioning. Show what you've tried and ask why it doesn't work (if it doesn't work). See [how to ask](http://stackoverflow.com/help/how-to-ask). – Peter Wood Aug 09 '15 at 07:10