'Python Program wont ever return "True"
So, I am working on this programming project, and these are the instructions for the project:
A list is sorted in ascending order if it is empty or each item except the last one is less than or equal to its successor. Define a predicate isSorted that expects a list as an argument and returns True if the list is sorted, or returns False otherwise. (Hint: For a list of length 2 or greater, loop through the list and compare pairs of items, from left to right, and return False if the first item in a pair is greater.)
This is what I made:
def isSorted(lst):
for x in range(len(lst) - 1):
if(lst[x] > lst[x + 1]):
return False
return True
# Testing
print(isSorted([]))
print(isSorted([1,2,3,4,5]))
print(isSorted([1,2,3,6,5]))
And these are the results I get: My Program
I cant figure our why I don't get "True" as a result for the third line in the "Testing" part of the program. Any help would be greatly appreciated!
Edit:
I tried unindenting the return true
portion of the program, but now i get back the following error:
File <string>, line 5
return True
^
SyntaxError: 'return' outside function
Solution 1:[1]
As commented, the second if statement being indented on the same level is "dead code"
You can rewrite your loop and return statements using all()
def isSorted(lst):
return all(lst[x] < lst[x + 1] for x in range(len(lst) - 1))
Solution 2:[2]
Should be better like this
def isSorted(lst):
for x in range(len(lst) - 1):
if(lst[x] > lst[x + 1]):
return False
return True
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Peterrabbit |
