Jupyter Snippet CB2nd 01_py3

Jupyter Snippet CB2nd 01_py3

Using the latest features of Python 3

my_list = list(range(10))
print(my_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(*my_list)
0 1 2 3 4 5 6 7 8 9
print(*my_list, sep=" + ", end=" = %d" % sum(my_list))
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
first, second, *rest, last = my_list
print(first, second, last)
0 1 9
rest
[2, 3, 4, 5, 6, 7, 8]
from math import pi, cos
α = 2
π = pi
cos(α * π)
1.000
a, b = 1, 2
f"The sum of {a} and {b} is {a + b}"
'The sum of 1 and 2 is 3'
def kinetic_energy(mass: 'kg', velocity: 'm/s') -> 'J':
    """The annotations serve here as documentation."""
    return .5 * mass * velocity ** 2
annotations = kinetic_energy.__annotations__
print(*(f"{key} is in {value}"
        for key, value in annotations.items()),
      sep=", ")
mass is in kg, velocity is in m/s, return is in J
import numpy as np
M = np.array([[0, 1], [1, 0]])
M * M
array([[0, 1],
       [1, 0]])
M @ M
array([[1, 0],
       [0, 1]])
def gen1():
    for i in range(5):
        for j in range(i):
            yield j
def gen2():
    for i in range(5):
        yield from range(i)
list(gen1())
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
list(gen2())
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
import time


def f1(x):
    time.sleep(1)
    return x
%timeit -n1 -r1 f1(0)
1 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -n1 -r1 f1(0)
1 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
from functools import lru_cache


@lru_cache(maxsize=32)  # keep the latest 32 calls
def f2(x):
    time.sleep(1)
    return x
%timeit -n1 -r1 f2(0)
1 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -n1 -r1 f2(0)
6.14 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
from pathlib import Path
p = Path('.')
sorted(p.glob('*.md'))
[PosixPath('00_intro.md'),
 PosixPath('01_py3.md'),
 PosixPath('02_workflows.md'),
 PosixPath('03_git.md'),
 PosixPath('04_git_advanced.md'),
 PosixPath('05_tips.md'),
 PosixPath('06_high_quality.md'),
 PosixPath('07_test.md'),
 PosixPath('08_debugging.md')]
_[0].read_text()
'# Introduction\n\n...\n'
[d for d in p.iterdir() if d.is_dir()]
[PosixPath('images'),
 PosixPath('.ipynb_checkpoints'),
 PosixPath('__pycache__'),
list((p / 'images').iterdir())
[PosixPath('images/github_new.png'), PosixPath('images/folder.png')]
import random as r
import statistics as st
my_list = [r.normalvariate(0, 1) for _ in range(100000)]
print(st.mean(my_list),
      st.median(my_list),
      st.stdev(my_list),
      )
0.00073 -0.00052 1.00050