Lily's Homework

  • + 0 comments

    Solution in Python 3

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    #
    # Complete the 'lilysHomework' function below.
    #
    # The function is expected to return an INTEGER.
    # The function accepts INTEGER_ARRAY arr as parameter.
    #
    
    def countSwaps(arr, r):
        arr = arr.copy()
        target = sorted(arr, reverse = r)
        inds = {v:i for i,v in enumerate(target)}
        i = 0
        count = 0
        while i < len(arr) and arr != target:
            while arr[i] != target[i]:
                ind = inds[arr[i]]
                arr[i], arr[ind] = arr[ind], arr[i]
                count += 1
            i += 1
        return count
    
    def lilysHomework(arr):
        #Write your code here
        return min(countSwaps(arr, False), countSwaps(arr, True))
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = int(input().strip())
    
        arr = list(map(int, input().rstrip().split()))
    
        result = lilysHomework(arr)
    
        fptr.write(str(result) + '\n')
    
        fptr.close()