4

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:

a = int(input("Enter a 4-digit number: "))

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

if b[0] > b[1]:
    print "Not ascending"
elif b[1] > b[2]:
    print "Not ascending"
elif b[2] > b[3]:
    print "Not ascending"
else:
    print "Ascending!"

My question is, how can I make it so that there's no limit on the amount of digits entered? So if someone enters a 7 digit number it does the same process up to the last digit.

Alpha Moses
  • 49
  • 1
  • 1
  • 2

3 Answers3

3

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"
Frank AK
  • 1,705
  • 15
  • 28
0

You would need a loop.

for example:

a = int(input("Enter a 4-digit number: "))

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


def isAscending(b):
  #loop for as many digits in the array
  for x in range(0, len(b) - 1):
    # if the next number is less than the previous return false
    if b[x] > b[x+1]:
      return False
  #  did not fail so return true
  return True

if isAscending(b):
  print ("the number is in ascending order")
else:
  print ("the number is not in ascending order")
ICP
  • 97
  • 10
0

If you're working with such a small number of digits, just create a new list w/ the elements in ascending order. Fortunately, Python has a function that does exactly that, the built-in function sorted:

def is_ascending(lst):
    return sorted(lst) == lst
Brian Rodriguez
  • 4,250
  • 1
  • 16
  • 37