对于以下函数,如果数字按降序排列,我试图返回True,如果数字不是,则尝试返回false。
'digits'必须是正整数
这是我的代码:
def rev_num_sort(digits):
n = len(digits)
for i in range n:
if digits[i] < digits[i+1]
return False
return True
E.g。
print rev_num_sort(321)
True
print rev_num_sort(123)
False
我知道你不能占用int的长度而且我在运行print语句时遇到了这个错误,但我不确定如何在不查找长度的情况下解决它。
答案 0 :(得分:7)
>>> 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
和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
答案 1 :(得分:2)
这是一个避免列表副本的短路版本
def rev_num_sort(digits):
digits = str(digits) # assuming digits is an int/long
all(digits[i-1] >= j for i, j in enumerate(digits) if i)
答案 2 :(得分:0)
我想整数操作,但我没有测试效率。
def isDigitsOrdered(digits) :
base = 10
lastNum = digits % base
while True:
base *= 10
tmpNum = digits % base / (base / 10)
if 0 == tmpNum and 0 == (digits/base):
break
if tmpNum >= lastNum :
return False
lastNum = tmpNum
return True
最后,我使用下面的案例测试自己的效率
#!/usr/bin/env python
import timeit
setup = """
def isDigitsOrdered(digits) :
base = 10
lastNum = digits % base
while True:
base *= 10
tmpNum = digits % base / (base / 10)
if 0 == tmpNum and 0 == (digits/base):
break
if tmpNum >= lastNum :
return False
lastNum = tmpNum
return True
def rev_num_sort(digits):
digits = str(digits) # assuming digits is an int/long
return all(digits[i-1] >= j for i, j in enumerate(digits) if i)
testdigits = (1234444444566788888999999999, 9999999998888876654444444321, 123456, 55667890)
gc.enable()
"""
testNum = 1000000
t1 = timeit.Timer("""
for d in testdigits :
isDigitsOrdered(d)
""", setup)
print t1.timeit(testNum)
t2 = timeit.Timer("""
for d in testdigits :
rev_num_sort(d)
""", setup)
print t2.timeit(testNum)
测试结果如下:
的 16.6870310307
45.7681000233 强>
通过整数运算显示时间成本比使用 GC启用的字符串快得多。
答案 3 :(得分:0)
def descending(n):
prevDplace = False
while n > 0:
n *= 0.1
currDplace = n%1
n = n - currDplace
if prevDplace:
if prevDplace > currDplace:
return False
else:
prevDplace = currDplace
return True
def rev_num_sort(digits):
digits = str(digits) # assuming digits is an int/long
all(digits[i-1] >= j for i, j in enumerate(digits) if i)
以下是gnibbler和我(类似于C先生)的性能比较,基于两者的时间分别为10000次(结果分别在元组中):
1234444444566788888999999999
9999999998888876654444444321
descending
:
(0.48712682723999023, 0.8589978218078613)
gnibbler
:
(0.1695241928100586, 0.69327712059021)
我发现这非常令人惊讶,字符串方法要快得多!