Hello, so I started with grabbing the indices of the actual numbers, since the input asks the user to include whitespace between the numbers. In the second step, I wanted to ensure there wouldn't essentially be an out of range issue so I checked to see if the last number in the list was less than the second to last, and if so, return 'Not sorted'. The final step loops through the list of indices and maps it to the original list to check if the number in the current iteration is greater than the number after it (the i + 2 is there to account for whitespace in the original list) and returns a message based on whether or not its true. Further checks could be done in the event that the user accidentally inputs a double space instead of just one or if they start the list off with a space instead of a number. Maybe a list.replace() or re.sub() would be appropriate but for simplicity's sake, I omitted those.
def is_sorted(x):
ind = [i for i,j in enumerate(x) if j.isnumeric()]
if x[ind[-1]] < x[ind[-2]]:
return x, 'Not sorted'
else:
for i in ind:
if x[i] > x[i+2]:
return x, 'The list is not sorted'
return x, 'The list is sorted'
if __name__ == '__main__':
listx = input('Please enter a list of numbers separated by a space: ')
is_sorted(listx)