Lily's Homework

  • + 2 comments

    In Python (I tried the simplest thing, and it worked):

    def lily_internal(a: list[int], reverse: bool=True):
        targets = {n: i for i, n in enumerate(sorted(a, reverse=reverse))}
        swaps = 0
        for i, n in enumerate(a):
            while i != targets[n]:
                # Swap the current value into the correct place.
                a[targets[n]], a[i] = n, a[targets[n]]
                swaps += 1
                n = a[i]
        return swaps
    
    def lilysHomework(a: list[int]):
        # lily_internal() is destructive, so send a copy the first time.
        return min(lily_internal(list(a), False), lily_internal(a, True))