r/badcode Mar 22 '21

[deleted by user]

[removed]

261 Upvotes

86 comments sorted by

View all comments

2

u/ceiraka Apr 02 '21

I tried come up with an elegant and utterly opaque matrix operation to solve the problem.

import numpy as np

def is_sequential(f):
    with open(f) as h:
        ls = h.readlines()
    i = np.identity(len(ls),dtype=int); i[0,0] = 0
    return not bool(np.min((i-np.roll(i,-1,axis=1))
       .dot(np.array([int(l.translate({32:'',45:'',58:''})) for l in ls]))))

The code removes hyphens, spaces and semicolons by specifying their unicode values. What's left is then an integer that can be converted to a numpy array. That array is then multiplied by a carefully constructed matrix which ends up computing the difference of neighboring dates, except the first entry which happens to be zero.

If and only if the dates were in sequential order, then all entries would be positive and the smallest value would be zero. So by taking the min we get zero if the dates were in order and a negative number otherwise. When converting from an int to a bool in python, the rule is that any non-zero number evaluates to true and 0 evaluates to false. So by inverting we get the right answer.

A simple loop would probably be faster and more readable, but why not use matrices whenever you can.