0

I'm trying to make a function that returns whether or not a List is in descending order by using recursion, but the variable descending seems to be changing from True back to False on its own. Also, I recognize this is likely not the best way to find descending order or even doing so with recursion (and I will gladly take suggestions); however, I would still like to understand this issue regardless if possible. The code is:

global descending
descending = False

def desOrder(numList):
    if not numList:
        descending = True
        return
    if max(numList) == numList[0]:
        del numList[0]
        desOrder(numList)
    return

numCopy = [5, 4, 3, 2, 1]
desOrder(numCopy)

if descending:
    return 0

I have tried adding print statements throughout to see where the source of the issue lies, but I have not been successful. desOrder(numCopy) will trigger the if not numList statement and change descending to True, but then the if descending statement is still recognizing descending to be False and not returning 0 as expected. Also, the numCopy variable is just an example for simplicity and in the actual program the desOrder function uses a copy of the desired List so the original is not altered. Thanks for any help

2
  • You need global descending. But it would be better if the function returned its result rather than setting a global variable. Commented Oct 20, 2023 at 20:42
  • This is a very inefficient algorithm. You don't need to check if the first element is the maximum, just check if it's more than the second element. And the recursion can stop when the list has 1 element. Commented Oct 20, 2023 at 20:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.