Checking lexicographic order python from text file

时间:2015-08-07 02:34:54

标签: python input lexicographic

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.

1 个答案:

答案 0 :(得分:0)

一种方法是读取文件,拆分行,将行按顺序排列,然后检查订单是相同还是不同。

这可能不是最有效的方法,但可行:

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

print sorted(potato_lines) == potato_lines

this question的答案向您展示如何在不进行排序的情况下进行检查。

例如,this answer提供了一种生成配对以检查顺序的简洁方法:

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))

然后你可以使用:

with open('potatoes.txt') as potatoes:
    print is_sorted(potatoes)