简体   繁体   中英

Ascending Order in Python

I'm trying to get this code to associate True with the variable is_ascending if the list numbers is in ascending order and False if otherwise

for i in range(2, len(numbers)) :
if numbers[i] < numbers[i-1] :
    is_ascending = False
    break
else :
    is_ascending = True

But the program im doing, this is for a class, says this won't work. Any help would be appreciated

You should use range(1, len(numbers)) as 1 means the second element and 0 index would refer to the first element. Besides that, your if-else statements should be inside the for loop (indentation issue). Your code works as below for a unsorted list and also for a sorted list. Try running it with numbers = [1,2,3,4,5] and it will print True

numbers = [1,2,4,3,5]

for i in range(1, len(numbers)):
    if numbers[i] < numbers[i-1]:
        is_ascending = False
        break
    else:
        is_ascending = True

print (is_ascending)        
> False

Bazingaa's answer is good and more readable to people not as familiar with functional programming. There's still two things you could improve on.

  • You could iterate over range(len(numbers) - 1) and compare each element with the next one instead of the previous. It's a personal preference but I find it more intuitive than the two-parameter notation of range .
  • You could use the all function as in this answer: https://stackoverflow.com/a/3755251/2813263

It would give you something like this:

is_ascending = all(numbers[i] <= numbers[i+1] for i in range(len(numbers) - 1))
if sorted(numbers) == numbers:
    is_ascending = True

That'll do it.

If you build a list of the outcome of the paired comparisons:

numbers = [10,20,30,40,20,50]
outcomes = [ numbers[i] > numbers[i-1] for i in range(1,len(numbers))]
print(outcomes)

This outputs:

[True, True, True, False, True]

The False is for the 40 & 20 comparison.

Then you can use all() to determine if the list is in ascending order

numbers = [10,20,30,40,50,60]
is_ascending = all([ numbers[i] > numbers[i-1] for i in range(1,len(numbers)) ])
print(is_ascending) # prints True
numbers = [10,5,20,30,40,50,60]
is_ascending = all([ numbers[i] > numbers[i-1] for i in range(1,len(numbers)) ])
print(is_ascending) # prints False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM