如何检查索引是否第N个索引应大于以前的索引

时间:2018-12-30 10:51:22

标签: python python-3.x

我想运行一个从0到1000的循环,我想打印一个比前一个数字低的数字“ ex:123 3大于2,而2大于1,所以打印123”,我尝试从1到100,然后如何检查1000个或更多数字

我试图将int输入转换为列表并用2位数字进行检查

no=int(input())
lis=[]
num_lis=[]
le=0

for i in range(10,no):
    lis=str(i)
    num_lis=[int (x)for x in lis]
    le=len(num_lis)-1
    if num_lis[le]>num_lis[le-1]:
        print(i)

从1到100没问题,我想检查三位数字是否像1 <2 <3,如果打印正确 我的代码只检查最后两位数字,如何检查三位和四位数字

2 个答案:

答案 0 :(得分:3)

您可以创建一个验证数字是否排序的函数:

def int_sorted(i):
    s = str(i)
    return s == ''.join(sorted(s, key=int))

print(int_sorted(123))
print(int_sorted(1234))
print(int_sorted(4234))

输出

True
True
False

请注意,sorted(s, key=int)通过使用sorteds参数根据每个数字的int值对key(数字字符串)进行排序。此功能与数字位数无关。

如果必须大于严格限制,则可以执行以下操作:

def int_sorted(i):
    s = str(i)
    sorted_s = sorted(s, key=int)
    return s == ''.join(sorted_s) and all(int(c) < int(n) for c, n in zip(sorted_s, sorted_s[1:]))

print(int_sorted(123))
print(int_sorted(1234))
print(int_sorted(4234))
print(int_sorted(99))

输出

True
True
False
False

答案 1 :(得分:3)

打印所有低于其后的数字:

您只需记住一个数字,如果下一个数字更大,则打印该数字:

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,