简体   繁体   中英

Can some one help me fix this list sorting code?

When I run this code it doesn't print anything? I've tried to invert the greater than less than but it's not helping.

def is_sorted(numbers):
    ''' Return whether or not the list of numbers is sorted '''

    for i in numbers:
        if numbers[i] < numbers[i + 1]:
            print('True')
        else:
            print('False')

for i in numbers in this case i is each number itself, not the index of each number. That would be for i in range(len(numbers)) though then [i + 1] would go out of bounds on the last iteration.

As an alternative, I would simplify that function to compare each element to the next element by zipping a slice of the list against another slice offset by one. By writing this as a generator expression within all this will short-circuit upon hitting the first False

def is_sorted(numbers):
    return all(i <= j for i, j in zip(numbers, numbers[1::]))

For example

>>> is_sorted([1,3,5,7])
True
>>> is_sorted([1,6,2,7,3])
False

Something like this should work:

def is_sorted(numbers):
    isSorted = True
    for i in numbers:
        try:
            if i > numbers[numbers.index(i)+1]:
                isSorted = False
        except:
            pass
    return isSorted
    
print(is_sorted([1,2],3,9,3))

You should add the variable, isSorted , because if i > next number , it would print False , but if i < next number , it would print True . You need the try and except , because if there was an error, if it was on the last number, it would be ignored. You also need to change i > numbers[i+1] to i > numbers[numbers.index(i)+1] , because to get the next number, we need to add 1 to the index, not the value.

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