>>> def rev_num_sort(num):
... strs = str(num)
... return strs == "".join(sorted(strs, reverse=True))
...
>>> rev_num_sort(321)
True
>>> rev_num_sort(123)
False
>>> rev_num_sort(510)
True
使用zip
and any
,不需要排序:
>>> def rev_num_sort(num):
... strs = str(num)
... return all(int(x) > int(y) for x, y in zip(strs, strs[1:]))
...
>>> rev_num_sort(321)
True
>>> rev_num_sort(123)
False
>>> rev_num_sort(510)
True
使用itertools.izip
和迭代器的内存高效版本:
>>> from itertools import izip
>>> def rev_num_sort(num):
... strs = str(num)
... it1 = iter(strs)
... it2 = iter(strs)
... next(it2)
... return all(int(x) > int(y) for x, y in izip(it1, it2))
...
>>> rev_num_sort(321)
True
>>> rev_num_sort(123)
False
>>> rev_num_sort(510)
True