function largestOfFour(arr) {
let results = []; //аккамулятор результатов
for (let i = 0; i < arr.length; i++) { //для каждой строки матрицы arr
let largestNumber = arr[i][0]; //пердпологаем, что первое число в строке является максимальным
for (let j = 1; j < arr[i].length; j++) { //для всех чисел в строке, начиная со второго
if (arr[i][j] > largestNumber) { // если текущее число больше нашего текущего максимума
largestNumber = arr[i][j]; // обновляем значение максимума
}
}
results[i] = largestNumber; //кладём текущий максимум в аккамулятор
}
return results; //возвращаем аккамулятор как результат работы функции
}
position =alphabet.find('я') # 31
newPosition = position + key # 36
alphabet [newPosition] # ааааа! нет такой буквы
position =s.find('я') # 31
newPosition = (position + key) % len(alphabet) # 4
alphabet [newPosition] # д
marks = {
'a' : [1,2,3],
'b' : [0,1,2],
'c' : [5,6,6],
'd' : [4,4,4]
}
def mean(lst):
return sum(lst) / len(lst)
sortedIds = sorted(marks.keys(), key=lambda studentId: mean(marks[studentId]))
print('лучший:', sortedIds[-1])
print('худший:', sortedIds[0])
лучший: c
худший: b
cursor.execute(clause, props)
result = cursor.fetchall()
with sqlite3.connect(`Ваши параметры подключения`, timeout=`Какое-то зверски большое число секунд, которое мы готовы "стоять в очереди"`) as connect:
# создаём подключение к базе которое существует только в рамках блока with
# то что мы здесь напишем должно отработать максимально быстро
cursor = connect.cursor()
cursor.execute(clause, props)
result = cursor.fetchall()
import psutil
import win32gui
import win32process
def enum_window_callback(hwnd, pid):
tid, current_pid = win32process.GetWindowThreadProcessId(hwnd)
if pid == current_pid and win32gui.IsWindowVisible(hwnd):
windows.append(hwnd)
for process in psutil.process_iter():
pid = process.pid
windows = []
win32gui.EnumWindows(enum_window_callback, pid)
windownames = [win32gui.GetWindowText(item) for item in windows]
if len(windownames):
exeName = process.name()
for windowName in windownames:
hwnd = win32gui.FindWindow(None, windowName)
print(f'"{exeName}" - "{windowName}" - "{hwnd}"')
"NVIDIA Share.exe" - "NVIDIA GeForce Overlay" - "66250"
"Code.exe" - "list of windows.py - grabscrren - Visual Studio Code" - "459882"
"Code.exe" - "● N-mer-Krammer.py - Рандомный habr - Visual Studio Code" - "132316"
"Battle.net.exe" - "Battle.net" - "132384"
"explorer.exe" - "" - "65860"
"explorer.exe" - "D:\" - "263030"
"explorer.exe" - "" - "65860"
"explorer.exe" - "" - "65860"
"explorer.exe" - "" - "65860"
"explorer.exe" - "" - "65860"
"explorer.exe" - "Program Manager" - "131380"
"python.exe" - "Jupyter Notebook" - "1639536"
"chrome.exe" - "Получение количества открытых окон через WinApi? — Хабр Q&A - Google Chrome" - "1442268"
import win32gui
import win32process
import win32api
import win32process
import win32con
def enum_window_callback(hwnd, _):
if win32gui.IsWindowVisible(hwnd):
tid, current_pid = win32process.GetWindowThreadProcessId(hwnd)
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, current_pid)
proc_name = win32process.GetModuleFileNameEx(handle, 0)
windows.append({
"hwnd":hwnd,
"pid" : current_pid,
"tid" : tid,
"window title" : win32gui.GetWindowText(hwnd),
"process name" : proc_name
})
windows = []
win32gui.EnumWindows(enum_window_callback, None)
for window in windows:
print(f'"{window["process name"]}"', window['pid'], f'"{window["window title"]}"', window['hwnd'], sep=' - ')
"C:\Windows\explorer.exe" - 8084 - "" - 65736
"C:\Users\Тоха\AppData\Local\Programs\Microsoft VS Code\Code.exe" - 6124 - "list of windows.py - grabscrren - Visual Studio Code" - 459882
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" - 11696 - "windows - How can I get process name using Python - Stack Overflow - Google Chrome" - 131222
"C:\Users\Тоха\AppData\Local\Programs\Microsoft VS Code\Code.exe" - 6124 - "● N-mer-Krammer.py - Рандомный habr - Visual Studio Code" - 132316
"C:\Qt\Tools\QtCreator\bin\qtcreator.exe" - 11308 - "main.cpp @ processScan - Qt Creator" - 1967294
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" - 11696 - "Получение количества открытых окон через WinApi? — Хабр Q&A - Google Chrome" - 1442268
"C:\Anaconda3\python.exe" - 9912 - "Jupyter Notebook" - 1639536
"C:\Program Files (x86)\Battle.net\Battle.net.exe" - 6396 - "Battle.net" - 132384
"C:\Windows\explorer.exe" - 8084 - "D:\" - 263030
"C:\Windows\SystemApps\MicrosoftWindows.Client.CBS_cw5n1h2txyewy\InputApp\TextInputHost.exe" - 12956 - "Microsoft Text Input Application" - 131658
"C:\Program Files\NVIDIA Corporation\NVIDIA GeForce Experience\NVIDIA Share.exe" - 5488 - "NVIDIA GeForce Overlay" - 66250
"C:\Windows\explorer.exe" - 8084 - "" - 65924
"C:\Windows\explorer.exe" - 8084 - "" - 65932
"C:\Windows\explorer.exe" - 8084 - "" - 65892
"C:\Windows\explorer.exe" - 8084 - "" - 65890
"C:\Windows\explorer.exe" - 8084 - "Program Manager" - 131380
XtX = X.T * X
result = inv(XtX).dot(X.T).dot(Y)
import numpy as np
K = 2 #степень целевой плоскости
points = np.array([[a, 5 + 2*a + 6 * a**2] for a in range(0, 60)]) # точки, по которым строим
class Symbolic:
def __init__(self, letter=None):
self.letters = dict() if letter is None else {letter : 1}
def addLetter(self, letter, power=1):
if letter not in self.letters:
self.letters[letter] = 0
self.letters[letter] += power
def __pow__(self, pow):
res = Symbolic()
for letter in self.letters:
res.letters[letter] = self.letters[letter] * pow
return res
def __mul__(self, right):
res = Symbolic()
for letter in self.letters:
res.addLetter(letter, self.letters[letter])
for letter in right.letters:
res.addLetter(letter, right.letters[letter])
return res
def __repr__(self):
return '*'.join(map(lambda letter: f'{letter}**{self.letters[letter]}', self.letters.keys()))
def pointsToPower(points, power):
result = points ** power
if points.shape[1] > 1 and power > 1:
for startpower in range(power-1, 0, -1):
for index in range(points.shape[1] - 1) :
base = np.array(points[:,index]) ** startpower
submatrix = pointsToPower(
points[:, index+1:],
power - startpower
)
result = np.hstack([result, np.array([submatrix[lineIndex, :] * base[lineIndex] for lineIndex in range(base.shape[0])])])
return result
def pointsToX(points, K=1):
return np.hstack([
# np.array([[1]] * points.shape[0]),
*[pointsToPower(points, power=i+1) for i in range(K)]
])
def krammer(X, sigma=1):
XtX = X.T.dot(X)
baseDet = np.linalg.det(XtX)
if baseDet == 0:
return [[None]]
Y = np.array([[sigma] * X.shape[0]]).T
return np.linalg.inv(XtX).dot(X.T).dot(Y)
X = pointsToX(points,K)
values = krammer(X).T[0]
if values[0] is None:
print('''Обратной матрицы не существует, и решить систему матричным методом невозможно.
В этом случае система решается методом исключения неизвестных (методом Гаусса).
Но его реализовывать мне влом''')
symbols = pointsToX(np.array([[Symbolic(chr(ord('a') + i)) for i in range(points.shape[1])]]),K)[0]print('Уравнение целевой плоскости:')
print(*[f'{value} * {symbol}' for symbol,value in zip(symbols, values)], sep=' + \n', end=' = 1')