编写一个接收整数n>0,并报告其数字(以10为基数(是否形成不递减序列(即,每个数字都大于或等于前一个数字(。
我在这个练习中遇到了麻烦。到目前为止,我的代码是:
def nondec(n):
'''
>>> nondec(113355779)
True
>>> nondec(44569)
True
>>> nondec(346234)
False
>>> nondec(222)
True
>>> nondec(789)
True
>>> nondec(55555)
True
>>> nondec(1234123)
False
>>> nondec(98765)
False
'''
prev = 9
while n>0 :
lastdigit = n%10
if lastdigit > prev:
return False
prev = lastdigit
n = n/10
return True
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
它适用于所有情况,但对于重复数字的情况除外:22255555。我尝试了很多方法,但这让我的代码变得更糟。谢谢
也许这就是您要查找的代码:
def nondec(n):
'''
>>> nondec(113355779)
True
>>> nondec(44569)
True
>>> nondec(346234)
False
>>> nondec(222)
True
>>> nondec(789)
True
>>> nondec(55555)
True
>>> nondec(1234123)
False
>>> nondec(98765)
False
'''
prev = 9
while n>0 :
lastdigit = n % 10
if lastdigit > prev:
return False
prev = lastdigit
n = n // 10
return True
我对您的代码所做的唯一更改是对您使用10:n = n / 10
进行除法的部分。
问题是,这个部门返回了一个float
,但你想要一个int
例如,如果取222
除以10
,则n
的新值为22.2
,而您希望它为22
。(您可以通过打印您编写的每一行代码的结果来检查此类问题!(
您可以使用//
而不是/
来完成此操作。
你可以检查这个答案Python除以10,看看我在说什么
您可以这样做:
def nondec(n):
return all(int(x)<=int(y) for x,y in zip(str(n), str(n)[1:]))
测试:
for n in (113355779,44569,346234,222,789,55555,1234123,98765):
print(n, nondec(n))
打印:
113355779 True
44569 True
346234 False
222 True
789 True
55555 True
1234123 False
98765 False
由于'0'<'1' ... '8'<'9'
,您实际上可以一直使用字符串:
def nondec(n):
s=str(n)
return all(x<=y for x,y in zip(s, s[1:]))
# same result...
另一种更语言化的方法:
def nondec(n):
'''
>>> nondec(113355779)
True
>>> nondec(44569)
True
>>> nondec(346234)
False
>>> nondec(222)
True
>>> nondec(789)
True
>>> nondec(55555)
True
>>> nondec(1234123)
False
>>> nondec(98765)
False
'''
n = str(n)
for e,_ in enumerate(n):
if e:
if int(n[e]) < int(n[e-1]):
return False
return True
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
变量n
应该是一个整数。您应该在循环中将n
强制转换为int
。
def nondec(n):
'''
>>> nondec(113355779)
True
>>> nondec(44569)
True
>>> nondec(346234)
False
>>> nondec(222)
True
>>> nondec(789)
True
>>> nondec(55555)
True
>>> nondec(1234123)
False
>>> nondec(98765)
False
'''
prev = 9
while n > 0:
lastdigit = n % 10
if lastdigit > prev:
return False
prev = lastdigit
n = int(n / 10)
return True
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)