简体   繁体   中英

Check if int list in in ascending order with python

I need to find a function that checks whether or not a list is in ascending order via python and have it return either True or False. So far what I have is:

def is_sorted(list_of_ints):
    lists_of_lists = int()
    if len(lists_of_ints) in [0,1]:
        return True
    if lists_[0] <= lists_of_ints[1]:
        return is_sorted(lists_of_ints[1:])
    return False

But it's coming back with a Runtime Error. Could anyone tell me or at least point me in the right direction?

You didn't provide the details of the RuntimeError , but I'm guessing it was due to excessive recursion. Python is bad at deep recursion, making no attempt to optimize patterns like tail recursion, so when you write code like this that recurses n times (where n is the length of the original input), it's going to blow up when the input hits a fairly small length (by default, the maximum stack frame depth is 1000).

You need to find ways to limit recursion (say, perform log n recursive steps instead of n ), or perform the tests imperatively, looping without recursion.

The code you posted is also wrong in other ways (you have a lists_of_lists that's unused, and not even a list , list_ that's used but never defined, etc.), but even if you fix all that, the recursion issues will prevent it from working for even moderately sized inputs.

If the goal is to verify a list is wholly sorted, there are much nicer/simpler ways. For example:

# On Py2 only, to make zip a generator so all can short-circuit on first failure
from future_builtins import zip

def is_sorted(list_of_ints):
    return all(x <= y for x, y in zip(list_of_ints, list_of_ints[1:]))

Or to push all the work to the C layer in CPython:

from future_builtins import map # Only on Py2
from operator import le

def is_sorted(list_of_ints):
    return all(map(le, list_of_ints, list_of_ints[1:]))

Obviously, return list_of_ints == sorted(list_of_ints) is the simplest approach, but for unsorted inputs it would involve doing O(n log n) work to perform the sort; the code given above performs at most O(n) work, and usually far less than that for unsorted input since it can short-circuit on first mismatch.

Your problem is a bunch of wrong naming. You were inconsistent with what names you used, so many were undefined. I changed what names were used where, and the following is the updated code:

def is_sorted(list_of_ints):
    if len(list_of_ints) in [0,1]:
        return True
    if list_of_ints[0] <= list_of_ints[1]:
        return is_sorted(list_of_ints[1:])
    return False

You can have something much easier, however. Just compare to the sorted version:

def is_sorted(list_of_ints):
    return list_of_ints == sorted(list_of_ints)

There are several significant errors in your code: your variable names are inconsistent (ie you use several undeclared variables which I presume are supposed to be the same object), and you have a "list_of_lists" variable initialized as an integer. You're also using recursion in a situation that doesn't warrant it, which might lead to a recursion depth error. I think the latter would be the most likely cause of a RuntimeError , since an undeclared variable would lead to a NameError and iterating over an integer would cause a TypeError .

However, running your code gives me several NameErrors , and fixing those gave me a correct result -- so I'm not sure where the RuntimeError is coming from.

A RuntimeError is a general class for errors that don't fall under other specific categories, but there's usually a message associated with it.

A note about recursion: Recursion is generally discouraged in Python, because the accumulation of stack frames has a huge memory burden and there are nearly always more efficient and/or more readable ways to achieve the same task. Each time a function call is made, the interpreter has to allocate memory for it, and the function which called it remains on the stack (in memory) until it gets a return value back. Many other languages implement "tail-call optimization", which (long story short) vastly reduces the load on the call stack -- but, by deliberate design, python doesn't have this. Python caps both the depth of the call stack and the amount of memory it's allowed to use, and if you reach the limit it raises a RuntimeError .

Unless you're dealing with a very long list, deep tree, or a very space-expensive recursive function call, getting the recursion depth RuntimeError usually means your recursive algorithm is running ad infinitum (ie you never reach your base case).

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