Exercise 67

Write without using any predefined function a Python algorithm as a function which takes as parameter a list of integers L and which returns True if the list is arranged in ascending order and False if not.

Solution

def testSort (L):
# initialize a counter
count = 0
for i in range (0, len (L) -1):
if L [i]> L [i + 1]:
count = count + 1
if count> 0:
return False
else:
return True

# Example
L1 = [13, 11, 43, 7, 5, 25, 9]
L2 = [3, 11, 21, 27, 35, 41, 59]
print (testSort (L1)) # display False
print (testSort (L2)) # display True
Younes Derfoufi
my-courses.net

Leave a Reply