Code Monkey home page Code Monkey logo

Comments (2)

britonad avatar britonad commented on May 30, 2024

Really great primer, thank you!

from blog-comments.

westurner avatar westurner commented on May 30, 2024

From HN

From https://news.ycombinator.com/item?id=22644620 :

Average of a finite series

There's a statistics module in Python 3.4+:

X = [1, 2, 3]

from statistics import mean, fmean
mean(X)

# may or may not be preferable to
sum(X) / len(X)

https://docs.python.org/3/library/statistics.html#statistics.fmean

Product of a terminating iterable

import operator
from functools import reduce
# from itertools import accumulate
reduce(operator.mul, X)

https://docs.python.org/3/library/functools.html#functools.reduce

Vector norm

from numpy import linalg as LA
LA.norm(X)

https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html

Function domain and range

Function domains and ranges can be specified and checked at compile-time with type annotations or at runtime with type()/isinstance() or with something like pycontracts or icontracts for checking preconditions and postconditions.

isinstance() and type()

from numbers import Number
from fractions import Fraction
from decimal import Decimal
x_fraction = Fraction("1/2") or Fraction(1, 2)
x_decimal = Decimal("0.3")
assert isinstance(x_fraction, Fraction)
assert isinstance(x_fraction, Number)
assert type(x_decimal) == Decimal
assert type(1j) == complex

Type annotations

from numbers import Number
from typing import Callable, Iterable, Optional, Union

def sum(a: int, b: int) -> int:
    return a + b

def sum(a: float, b: Number) -> Number:
    return a + b

def sum(a: Number, b: Number) -> Union[Number, None]:
    return a + b if not (a is None or b is None) else None

def sum(a: Number, b: Number) -> Optional[Number]:
    return a + b if not (a is None or b is None) else None

def sum(a: Number, b: Number) -> Optional[Number]:
    if not isinstance(a, Number):
        raise TypeError(("a is not a", Number))
    return a + b if not (a is None or b is None) else None
def map(function: Callable, sequence: Iterable) -> Iterable:
    return (function(x) for x in sequence)

Preconditions and Postconditions and Design-By-Contract

def sum(a: Number, b: Number) -> Optional[Number]:
    # preconditions
    if not isinstance(a, Number):
        raise TypeError(("a is not a", Number, "a is a", type(a)))
    if a < 0:
        raise ValueError(("a is < 0", a))

    # function ("command" in Hoare Logic)
    if b is None:
        return None
    a_ = a
    output = a_ + b

    # postconditions
    assert isinstance(output, (Number,  bool, int, float, complex, Fraction, Decimal))
    assert a == a_  # "invariance"
    # a['num1'] += 1; assert a['num1'] == a['num1']

    return output
import pytest

def test_sum():
    assert sum(False, True) == 1

    with pytest.raises(TypeError):
        sum(None, 0)
    with pytest.raises(ValueError):
        sum(-1, 0)

    assert sum(1, None) == None

# !pip install pytest-cov
# !pytest -v --cov=this_file --cov-report=term-missing ./this_file.py
test_sum()

In addition to as conditionals that raise subclasses of Exception like TypeError and ValueError and assertions that raise AssertionError,
runtime-checked preconditions and postconditions can be specified as annotations, decorators, or in docstrings:

Dot product

Y = [4, 5, 6]
np.dot(X, Y)

https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html

Unit vector

X / np.linalg.norm(X)

Also

Exponentiation and XOR

x**3    # x*x*x
x**1/2  # math.sqrt(x)

x^2   # x XOR 2
x^3   # operator.xor(x, 3)

Matrix multiplication operator

import numpy as np
a = np.matrix([[1, 0], [0, 1]])
b = np.matrix([[4, 1], [2, 2]])
assert a @ b == np.matmul(a, b)
p.testing.assert_equal(np.matmul(a,b), a @ b)

from blog-comments.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.