Best way to find the largest sorted suffix in a list - USACO Sleepy Cow Sorting Python Solving this problem.
Right now, my solution entails finding the largest sorted sublist, starting from the beginning, all the way to the end. However, I feel like the way I wrote the sorted_sublist function can definitely be improved. Besides that, I'm looking for any way to improve the way I write my code.
My code:
with open(&quot;sleepy.in&quot;, &quot;r&quot;) as fin:
  n = int(next(fin))
  nums = [int(i) for i in fin.readline().split()]

def sorted_sublist(n, nums):
  for i in range(n):
    sublist = nums[i:n]
    if sublist == sorted(sublist):
      return sublist

def main(n, nums):
 x = sorted_sublist(n, nums)
 return n - len(x)

with open(&quot;sleepy.out&quot;, &quot;w+&quot;) as fout:
 print(main(n, nums), file=fout)

Problem synopsis:
Given a list of numbers, find the number of steps it would take to sort this list by repeatedly placing the first element of this list into another slot, provided that you do this in an optimal fashion.
Example:
Input:
4
4 3 2 1

Step 1. Place the 4 to the back of the list: 3, 2, 1, 4
Step 2. Place the 3 to the third index of the list: 2, 1, 3, 4
Step 3. Place the 2 to the second index of the list: 1, 2, 3, 4
Output: 3, as it took three optimal steps to reach a sorted list
Nice solution and implementation. Few suggestions:

Naming: the name main is generally used for the entry point of the program. In this case, a better name could be steps_to_sort_cows.
Sublist bounds: since n is fixed, instead of sublist = nums[i:n] you can write sublist = nums[i:]

Complexity
The time complexity is \$O(n*n*log(n))\$. Basically, for each cow sort all the remaining cows. Typically, it's considered not optimal for large inputs.
The space complexity is also not optimal. For each cow two lists are created, one for the new sublist and one for the sorted sublist.
Improved
To reduce space and time complexity, find the size of the sorted sublist in this way:
def steps_to_sort_cows(n, cows):
  first_sorted_cow = cows[-1]
  sorted_cows = 0
  for c in reversed(cows):
    if c &gt; first_sorted_cow:
      return n - sorted_cows
    first_sorted_cow = c
    sorted_cows += 1
  return 0

Starting from the end, count the number of sorted cows and then return n - sorted_cows.
This approach takes \$O(n)\$ time and \$O(1)\$ space complexity.