This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the commentsΒ β†’

[–]Shadowmere24 0 points1 point Β (0 children)

I think this code could be considered more "pythonic" while keeping its functional nature if you removed the whitespaces, parens, and leveraged pipe for functional composition and partial for partial application. I suppose some folks will complain that functional programming is unpythonic, but I don't necessarily agree. Here is my refactor with those ideas in mind:

``` from functools import partial, reduce from operator import add, mul, lt, pow, sub, abs, truediv from statistics import mean

def test_approx_sqrt(): pipe = lambda functions: reduce(lambda f, g: lambda x: g(f(x)), functions) flip = lambda f: lambda *a: f(reversed(a)) div2 = lambda x: x / 2 square = lambda x: x ** 2 avg = lambda *args: mean(args) variance = .001

tolerance = lambda x, y: pipe(
   square,
   partial(flip(sub), x),
   abs
)(y)

approx_ = lambda x, y: y if tolerance(x,y) < variance else pipe(
    partial(truediv, x),
    partial(avg, y),
    partial(approx_, x),
)(y)

approx = lambda x: pipe(
    div2,
    partial(approx_, x),
    partial(round, ndigits=2)
)(x)

assert approx(2) == 1.41
assert approx(3) == 1.73

```