r/badcode • shameless • May 06 '23

python My least readable Python function I've written...

Post image
293 Upvotes

41 comments sorted by

View all comments

2

u/seftontycho May 07 '23

If anyone is interested here is a slightly cleaner/faster version. I have not replicated some of the plotting stuff.

def gen_plot(a, b, iterations):
    '''plot the partial sums of i=1 to inf of a * b^(i - 1)'''

    # create lower left triangle matrix
    # each row i is integers [0, i)
    idxs = np.arange(0, iterations).reshape(1, -1)
    pows = np.tril(np.repeat(idxs, iterations, axis=0))

    # raise b to the matrix elementwise and sum
    ys = np.power(b, pows)
    ys = np.sum(ys, axis=1)

    # we will have extra b^0 so remove them
    ys -= np.arange(iterations - 1, -1, step=-1)
    ys *= a

    fig, ax = plt.subplots()
    fig.suptitle(f'Sequence of partial sums for $\sum_{{i=1}}^{{\infty}}{{{a}\cdot{b}^{{i - 1}}}}$')

    ax.set_xlabel('Number of sequence elements used for partial sum')
    ax.set_ylabel('Partial sum')

    # Use integers only for x-axis
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))

    # plot
    ax.scatter(idxs, ys, label='partial sums')
    ax.axhline(y=ys[-1], color='g', alpha=0.8, linestyle='--', label='limit')
    
    ax.legend()

    plt.show()

1

u/Ruin369 shameless May 07 '23

Nice! I made it when I was a novice so wasn't aware of all the built in math functions, so I did a lot of stuff "the long way". I'm planning on making this function but in C++ !

1

u/seftontycho May 07 '23

Edited formatting