Comments (2)
Really great primer, thank you!
from blog-comments.
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)
- https://docs.python.org/3/library/typing.html :
Note The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
- https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
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 assert
ions that raise AssertionError
,
runtime-checked preconditions and postconditions can be specified as annotations, decorators, or in docstrings:
- https://en.wikipedia.org/wiki/Design_by_contract
- https://pypi.org/project/PyContracts/
- https://pypi.org/project/icontract/
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)
- 2020/06/google-colaboratory-tips/ HOT 6
- 2020/06/fastapi-vs-flask/ HOT 17
- 2020/03/illustrated-simclr/ HOT 32
- 2020/08/information-retrieval-evaluation/ HOT 6
- 2020/06/fasttext-embeddings/ HOT 8
- vscode-on-colab/ HOT 25
- 2020/02/tensorflow-hub-for-transfer-learning/
- 2020/02/albert-visual-summary/ HOT 3
- keyphrase-extraction/ HOT 1
- knowledge-transfer/ HOT 7
- 2020/03/fixmatch-semi-supervised/ HOT 5
- interactive-sentence-embeddings/ HOT 2
- 2019/12/migrating-to-pathlib/ HOT 3
- 2020/07/semi-supervised-learning/ HOT 6
- 2020/04/deepcluster/ HOT 7
- regex/ HOT 6
- 2020/03/illustrated-pirl/ HOT 1
- 2018/10/django-orm-for-sql-users/ HOT 2
- 2020/04/illustrated-self-labelling/ HOT 4
- 2019/03/automate-ssh-commands/ HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog-comments.