import numpy as np
from numba import njit
# С использованием numpy
def max_divisors_v1(n):
divs = np.ones(n + 1, np.uint8)
for step in range(2, n + 1):
divs[step::step] += 1
divs[0] = 0
num = divs.argmax()
return num, divs[num]
# Без numpy, чистый Python
def max_divisors_v2(n):
divs = [1] * (n + 1)
for step in range(2, n + 1):
for index in range(step, n + 1, step):
divs[index] += 1
divs[0] = 0
cnt = max(divs)
num = divs.index(cnt)
return num, cnt
# JIT-компиляция с декоратором @njit
max_divisors_v3 = njit(max_divisors_v2)
matchobj = re.search(...)
if matchobj:
crypto = matchobj.group()
import cv2
import numpy as np
data = """1 -9 -2 8 6 1
8 -1 -11 -7 6 4
10 12 -1 -9 -12 14
8 10 -3 -5 17 8
6 4 10 -13 -16 19"""
# matrix = np.random.randint(-128, 128, (1000, 1000), dtype=np.int32)
matrix = np.int32([line.split() for line in data.splitlines()])
def find_max_kernel(matrix, border=cv2.BORDER_ISOLATED):
max_area = 0
mask = np.float32(matrix < 0)
ones = np.ones_like(mask)
conv_x = np.zeros_like(mask)
conv_y = np.zeros_like(mask)
max_h, max_w = mask.shape
for h in range(1, max_h + 1):
cv2.filter2D(mask, -1, ones[:h, None, 0], conv_y, (0, 0), 0, border)
for w in range(1, max_w + 1):
area = h * w
if area > max_area:
cv2.filter2D(conv_y, -1, ones[None, 0, :w], conv_x, (0, 0), 0, border)
if conv_x.max() == area:
max_area, shape = area, (h, w)
else:
if w == 1:
max_h = h - 1
if h == 1:
max_w = w - 1
break
if h >= max_h:
break
cv2.filter2D(mask, -1, np.ones(shape, np.float32), conv_x, (0, 0), 0, border)
p1 = np.array(np.unravel_index(conv_x.argmax(), conv_x.shape))
p2 = p1 + shape - 1
return p1, p2
print(*find_max_kernel(matrix), sep='\n')
import numpy as np
from itertools import zip_longest
lst = [[1, 2, 3], [4, 5, 6, 7, 8], [9, 10, 11]]
def neighbors(a, b, m=lst, r=1):
m = np.array(list(zip_longest(*m)))#.T
v = np.argwhere(m == b) - np.argwhere(m == a)
return np.abs(v).max() <= r
assert neighbors(1, 2) == True
assert neighbors(1, 6) == False
assert neighbors(5, 6) == True
assert neighbors(3, 6) == True
assert neighbors(7, 11) == True
assert neighbors(1, 9) == False
assert neighbors(7, 8) == True
from collections import Counter
lst = ['a', 'c', 'f', 'r', 'a', 'a', 'f']
lst.sort() # не обязательно
result = Counter(lst)
import numpy as np
N = 20
numbers = np.random.randint(0, 40, N)
print('Исходный массив:', *numbers)
print('Уникальные пары: ', end='')
numbers.sort()
cache = set()
for index in np.argwhere(np.diff(numbers) == 1):
pair = numbers[index.item():][:2]
if cache.isdisjoint(pair):
cache.update(pair)
print(*pair, sep='-', end=' ')
Исходный массив: 28 10 24 19 17 0 20 24 5 30 26 39 6 38 31 39 28 25 18 24
Уникальные пары: 5-6 17-18 19-20 24-25 30-31 38-39
>>> import numpy as np
>>> np.math.factorial(np.arange(6))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: only size-1 arrays can be converted to Python scalars
>>> factorial = np.vectorize(np.math.factorial)
>>> factorial(np.arange(6))
array([ 1, 1, 2, 6, 24, 120])