Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you know if your list is ascending in python [duplicate]

Tags:

python

I wrote this program in python to see if a list is ascending and its not working, can someone help me?

list1 = [1, 2, 3, 4]
print (list1)
length = len(list1)
run_started = False
for x in range(length - 1):
    t = list1[x + 1] - list1[x]
    if t > 0 :
        if run_started:
            run_length = x
        else:
            run_started = True
            run_length = x
    else:
        if run_started:
            print (True)
            print ("Run Length: {0}".format(run_length))
            break
if not run_started:
    print (False)
like image 905
user2980776 Avatar asked Nov 11 '13 21:11

user2980776


2 Answers

I'd say the easiest (although not the most efficient) way would be:

list1 = [3, 1, 2, 4]

if sorted(list1) == list1:
    print "list1 is sorted"
like image 104
jbat100 Avatar answered Oct 22 '22 10:10

jbat100


Well, here's my go at it. Some have suggested sorting the list, which would be O(nlogn). I propose a simpler O(n) solution

def isAscending(list):
    previous = list[0]
    for number in list:
        if number < previous:
            return False
        previous = number
    return True
like image 31
slider Avatar answered Oct 22 '22 11:10

slider