Alterna · учебный материал

Imports and mathematics

Imports to Python, math, decimal, fractions, statistics and combinatorics: when a standard library makes a decision clearer.

Что в этом материале

Содержание и основные понятия

import math
Leaves visible the origin of the function:
math.gcd(a, b)
It's more accurate than a nameless challenge.
Standard library
10 to 11 grades
EEG: algorithmic support
01
Three forms of imports
Recording
When appropriate
Risk
import math
Normal choice: The source of the function is visible in every call.
Almost not.
from math import gcd
One or two very frequent functions in a short module.
The origin of the name is becoming less visible.
import math as m
Only if the cut is accepted in the project and obviously the reader.
A bad alias masks the meaning.
Important
from math import *
Do not use: names may encounter built-in functions or program variables.
02
Tools for numbers
math
gcd
,
lcm
,
isqrt
,
comb
,
perm
,
ceil
and
floor
.
decimal
Decimal money and fixed accuracy, doesn't cure the wrong model, but avoids the binary error.
float
.
fractions
Fraction
Keeps the rational number accurate: it's convenient for explanations and symbols.
statistics
Medium, median, fashion.
sum(values) / len(values)
.
random
Generates test data and simulates randomity. Not appropriate for passwords and secrets.
operator
itemgetter
and
attrgetter
Gives reading keys to sorting, but normal
lambda
It's often clearer.
03
Combinatorium without IEDs
Number of ways to choose
k
of objects from
n
without order equals
math.comb(n, k)
B. Order changes
math.perm(n, k)
The functions return the whole number and correctly process the high values.
import
math
n, k = 6, 2
print(math.comb(n, k))
print(math.perm(n, k))
For six objects and two choices, you get 15 combinations and 30 locations: in the second case, the order of the selected pair is important.
04
Quick check
What call returns an entire portion of the square root and does not lose accuracy on large wholes?

Structural map of textbooks