Comparing digits in an integer in Python

后端 未结 3 998
慢半拍i
慢半拍i 2021-01-16 12:48

Really need some help here. Super early in learning Python.

The goal is to take a number and see if the digits are in ascending order. What I have so far is:

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 13:45

    First step sort all your input

    b = [int(i) for i in str(a)]
    

    Second step, compare the origin input with the sorted-list, all the element of the list can be concat with a string (digit-string), so you can compare them with only one time.

    c = sorted(b)
    
    ''.join([str(i) for i in b]) > ''.join([str(i) for i in c]):
    
       print "Not ascending"
    else:
       print "Ascending!"
    

    Or use the std lib, check every element with the next element just like your way:

    every_check = [b[i] <= b[i+1] for i in xrange(len(b)-1)]
    

    [True, True, False, False]

    and use all() check if all True

    if all(every_check):
        print "Ascending!"
    else:
        print "Not ascending"
    

提交回复
热议问题