Anybody know what this is? II

a = [1,2,3,4,5,6,7,8,9]
b = [10,11,12,13,14,15,16,17,18,19]

def p(x):
    return len(x) % 2 * 1

def px(x):
    n = len(x) // 2
    m = n - 1
    if p(x):
        n += 1
    return (m, n) if m > -1 else []

Without dependency,

def px(x):
    p = lambda x: len(x) % 2 * 1
    n = len(x) // 2
    m = n - 1
    if p(x):
        n += 1
    return (m, n) if m > -1 else []

This seems to be a function that returns indices of the middle numbers in a list.

1 Like

Nearly correct. It finds a pivotal pair. If we want to reverse a sequence or list it determines whether we flip the inner pair (even length) or the outer pair on either side of the central element. Note the returns.

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Swapping the pivotal pair…

[10, 11, 12, 13, 15, 14, 16, 17, 18, 19]

With an odd length,

[1, 2, 3, 4, 5, 6, 7, 8, 9]

swapping…

[1, 2, 3, 6, 5, 4, 7, 8, 9]

The only missing step is iterating upwards from n and downwards from m to complete the swaps needed to reverse the sequence

def rx(x):
    m, n = px(x)  # dependency
    while m >= 0:
        x[n], x[m] = x[m], x[n]
        m, n = m - 1, n + 1
    return x
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> rx(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> rx(b)
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10]

What it simulates is using two hands to reverse a row of objects.

Let’s change b by subtracting 1 from every element…

b = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

Now picture them as the total on three dice in each position.

[(1, 3, 5), (1, 2, 7), .., (2, 7, 8), (3, 6, 9)]

Now we can picture one hand picking up three dice and the other hand three dice and swapping their location in the row. This would be akin to seeing it the way someone on the opposing side of the table would see it.

Algorithms of all sorts exist in our day to day. Above is just one example. Our code is emulating human actions. That is a good starting point in any problem. How would we do it on paper, or with physical objects? Of course once we get into the brass tacks we may write much slimmer code using built in objects, that stands to reason as optimization goes. However, sometimes optimization comes right down to using skimpy code like this. No tricks involved. Simple algo, is all.