打印所有小于后面的数字:
你可以简单地记住一个数字,如果下一个更大,就打印出来:
number = None
while number is None:
number = int(input("Input a number: "))
number = str(number)
last_digit = int(number[0])
for s in number[1:]:
this_digit = int(s)
if this_digit > last_digit:
print(last_digit, end="")
last_digit = this_digit
print(last_digit)
12354 的输出:
1235
这将打印所有小于下一个的数字。
检查数字是否“升序”:
要快速检查,您可以使用zip()。字符'0123456789' 按此顺序比较:'0'<'1'<'2'<'3'<'4'<'5'<'6'<'7'<'8'<'9' - 无需将其转换为整数,只需“按原样”比较字符即可:
def IsIncreasing(number):
n = str(number)
return all(a<b for a,b in zip(n,n[1:]))
这是如何工作的?
它从数字和数字移位 1 生成元组:
"123456789"
"23456789"
==> ('1','2'),('2','3'),...,('7','8'),('8','9') as generator of tuples
并使用all()确保所有第一个元素都小于第二个元素
例子:
for k in [1234,1,123456798]:
print(k,IsIncreasing(k))
输出(重新格式化):
1234 True
1 True
123456798 False
无需通过需要更多计算的排序进行比较。
测试从 1 到 1000 的所有数字:
您可以使用IsIncreasing() 函数创建从 1 到 1000 的所有“递增”数字的列表:
get_all_up_to_1000 = [k for k in range(1,1001) if IsIncreasing(k)]
print( *(f"{k:>3}," for k in get_all_up_to_1000))
输出:
1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15,
16, 17, 18, 19, 23, 24, 25, 26, 27, 28, 29, 34, 35,
36, 37, 38, 39, 45, 46, 47, 48, 49, 56, 57, 58, 59,
67, 68, 69, 78, 79, 89, 123, 124, 125, 126, 127, 128, 129,
134, 135, 136, 137, 138, 139, 145, 146, 147, 148, 149, 156, 157,
158, 159, 167, 168, 169, 178, 179, 189, 234, 235, 236, 237, 238,
239, 245, 246, 247, 248, 249, 256, 257, 258, 259, 267, 268, 269,
278, 279, 289, 345, 346, 347, 348, 349, 356, 357, 358, 359, 367,
368, 369, 378, 379, 389, 456, 457, 458, 459, 467, 468, 469, 478,
479, 489, 567, 568, 569, 578, 579, 589, 678, 679, 689, 789,