News for hackers. Stuff that matters.
Re:Pythonic monotonic by zzzeek on Friday August 13, 2021 @12:58PM (#28171501)
Here's two from me which just try to replicate the results of the original, it doesn't accommodate for values being the same or anything like that. This took me well over half an hour, I got more stuck on the first one trying to reduce the logic than I'd prefer to have, and I would have failed any job interview by now because I'm someone that's known to supposed to be "smart", but these things are always difficult for me to focus on.

    def mono_runs_pythonic_two(seq):
        curr = []

        result = []
        prev = None
        is_decreasing = None

        for elem in seq:
            if prev is not None:
                if (
                    elem < prev
                ) is not is_decreasing and is_decreasing is not None:

                    if is_decreasing:
                        curr.reverse()
                    if curr:
                        result.append(curr)
                        curr = []
                is_decreasing = elem < prev
            prev = elem
            curr.append(elem)

        result.append(curr)

        return result


    def mono_runs_pythonic_three(seq):
        def grouper():

            is_decreasing = False
            prev = None

            def go(elem):
                nonlocal is_decreasing, prev
                if prev is not None:
                    is_decreasing = elem < prev
                prev = elem
                return is_decreasing

            return go

        return [
            list(reversed(list(group))) if is_decreasing else list(group)
            for is_decreasing, group in itertools.groupby(seq, key=grouper())
        ]

There are no comments on this comment yet.