first commit

This commit is contained in:
2025-11-12 11:34:34 +03:00
commit 29280f3e50
77 changed files with 272246 additions and 0 deletions
Vendored
BIN
View File
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
{}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

File diff suppressed because one or more lines are too long
Binary file not shown.
+73
View File
@@ -0,0 +1,73 @@
import numpy as np
import typing
from collections import defaultdict
def kfold_split(
num_objects: int, num_folds: int
) -> list[tuple[np.ndarray, np.ndarray]]:
indices = np.arange(num_objects)
fold_size = num_objects // num_folds
result = []
for i in range(num_folds):
start = i * fold_size
if i == num_folds - 1:
end = num_objects
else:
end = (i + 1) * fold_size
val_indices = indices[start:end]
train_indices = np.concatenate([indices[:start], indices[end:]])
result.append((train_indices, val_indices))
return result
def knn_cv_score(
X: np.ndarray,
y: np.ndarray,
parameters: dict[str, list],
score_function: callable,
folds: list[tuple[np.ndarray, np.ndarray]],
knn_class: object,
) -> dict[str, float]:
results = {}
normalizers = parameters.get("normalizers", [(None, None)])
n_neighbors_list = parameters.get("n_neighbors", [5])
metrics_list = parameters.get("metrics", ["euclidean"])
weights_list = parameters.get("weights", ["uniform"])
for normalizer_tuple in normalizers:
normalizer, normalizer_name = normalizer_tuple
for n_neighbors in n_neighbors_list:
for metric in metrics_list:
for weight in weights_list:
fold_scores = []
for train_idx, val_idx in folds:
X_train, X_val = X[train_idx], X[val_idx]
y_train, y_val = y[train_idx], y[val_idx]
if normalizer is not None:
normalizer_fitted = normalizer.fit(X_train)
X_train = normalizer_fitted.transform(X_train)
X_val = normalizer_fitted.transform(X_val)
knn = knn_class(
n_neighbors=n_neighbors, metric=metric, weights=weight
)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_val)
score = score_function(y_val, y_pred)
fold_scores.append(score)
mean_score = np.mean(fold_scores)
key = (normalizer_name, n_neighbors, metric, weight)
results[key] = mean_score
return results
+76
View File
@@ -0,0 +1,76 @@
import numpy as np
import typing
from collections import defaultdict
def kfold_split(
num_objects: int, num_folds: int
) -> list[tuple[np.ndarray, np.ndarray]]:
all_indices = np.arange(num_objects)
fold_size = num_objects // num_folds
splits = []
for fold_idx in range(num_folds):
fold_start = fold_idx * fold_size
fold_end = (
num_objects if fold_idx == num_folds - 1 else (fold_idx + 1) * fold_size
)
validation = all_indices[fold_start:fold_end]
training = np.concatenate([all_indices[:fold_start], all_indices[fold_end:]])
splits.append((training, validation))
return splits
def knn_cv_score(
X: np.ndarray,
y: np.ndarray,
parameters: dict[str, list],
score_function: callable,
folds: list[tuple[np.ndarray, np.ndarray]],
knn_class: object,
) -> dict[str, float]:
cv_results = {}
normalizer_configs = parameters.get("normalizers", [(None, None)])
neighbor_counts = parameters.get("n_neighbors", [5])
distance_metrics = parameters.get("metrics", ["euclidean"])
weight_schemes = parameters.get("weights", ["uniform"])
for norm_obj, norm_label in normalizer_configs:
for num_neighbors in neighbor_counts:
for distance_metric in distance_metrics:
for weight_scheme in weight_schemes:
scores_per_fold = []
for train_indices, val_indices in folds:
X_tr, X_va = X[train_indices], X[val_indices]
y_tr, y_va = y[train_indices], y[val_indices]
if norm_obj is not None:
fitted_normalizer = norm_obj.fit(X_tr)
X_tr = fitted_normalizer.transform(X_tr)
X_va = fitted_normalizer.transform(X_va)
classifier = knn_class(
n_neighbors=num_neighbors,
metric=distance_metric,
weights=weight_scheme,
)
classifier.fit(X_tr, y_tr)
predictions = classifier.predict(X_va)
fold_score = score_function(y_va, predictions)
scores_per_fold.append(fold_score)
avg_score = np.mean(scores_per_fold)
param_key = (
norm_label,
num_neighbors,
distance_metric,
weight_scheme,
)
cv_results[param_key] = avg_score
return cv_results
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,161 @@
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from sklearn import neighbors
from sklearn.metrics import r2_score
from sklearn.preprocessing import MinMaxScaler
from cross_val import kfold_split, knn_cv_score
def test_split_0():
with open('cross_val.py', 'r') as file:
lines = ' '.join(file.readlines())
assert 'import numpy' in lines
assert 'import defaultdict' in lines
assert 'import typing' in lines
assert lines.count('import') == 3
assert 'sklearn' not in lines
def test_split_1():
X_1 = kfold_split(2, 2)
answer = [(np.array([1]), np.array([0])), (np.array([0]), np.array([1]))]
assert type(X_1) == list
assert_equal(X_1, answer)
def test_split_2():
X_1 = kfold_split(5, 3)
answer = [(np.array([1, 2, 3, 4]), np.array([0])),
(np.array([0, 2, 3, 4]), np.array([1])),
(np.array([0, 1]), np.array([2, 3, 4]))]
assert type(X_1) == list
assert_equal(X_1, answer)
def test_split_3():
X_1 = kfold_split(11, 7)
answer = [(np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), np.array([0])),
(np.array([ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10]), np.array([1])),
(np.array([ 0, 1, 3, 4, 5, 6, 7, 8, 9, 10]), np.array([2])),
(np.array([ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10]), np.array([3])),
(np.array([ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10]), np.array([4])),
(np.array([ 0, 1, 2, 3, 4, 6, 7, 8, 9, 10]), np.array([5])),
(np.array([0, 1, 2, 3, 4, 5]), np.array([ 6, 7, 8, 9, 10]))]
assert type(X_1) == list
assert_equal(X_1, answer)
def test_cv_4():
X_train = np.array([[2, 1, -1], [1, 1, 1], [0.9, -0.25, 7], [1, 2, -3], [0, 0, 0], [2, -1, 0.5]])
y_train = np.sum(X_train, axis=1)
parameters = {
'n_neighbors': [1, 2, 4],
'metrics': ['euclidean', 'cosine'],
'weights': ['uniform', 'distance'],
'normalizers': [(None, 'None')]
}
folds = kfold_split(6, 3)
out = knn_cv_score(X_train, y_train, parameters, r2_score, folds, neighbors.KNeighborsRegressor)
answer = {
('None', 1, 'euclidean', 'uniform'): -11.29188203967135,
('None', 1, 'euclidean', 'distance'): -11.29188203967135,
('None', 1, 'cosine', 'uniform'): -17.63280796559728,
('None', 1, 'cosine', 'distance'): -17.632807965597276,
('None', 2, 'euclidean', 'uniform'): -7.5333863756105215,
('None', 2, 'euclidean', 'distance'): -7.997305328982919,
('None', 2, 'cosine', 'uniform'): -4.246942433109774,
('None', 2, 'cosine', 'distance'): -6.7448165099645365,
('None', 4, 'euclidean', 'uniform'): -3.6194607932134364,
('None', 4, 'euclidean', 'distance'): -4.211377791660151,
('None', 4, 'cosine', 'uniform'): -3.6194607932134364,
('None', 4, 'cosine', 'distance'): -4.335691384752842
}
assert type(out) == dict
assert len(out) == len(answer)
for key in answer:
assert_allclose(answer[key], out[key])
def test_cv_5():
X_train = np.array([[ 0.62069296, -0.07097426, 0.65172896, -1.14620331],
[ 2.03347616, 0.32524614, -0.71941433, -0.30789854],
[ 0.17100377, 1.63120292, 1.34284446, -2.16397238],
[-1.65370417, 0.62499229, -0.50217293, 2.07813591],
[ 0.84667916, 0.25458428, 0.14720704, -0.18668345],
[ 0.43833344, -1.40348048, -1.37944118, 0.19192659],
[ 0.97229574, -0.54606276, -0.09855294, 1.28961291],
[ 0.25355626, -1.72816511, 0.084554 , -2.14256875],
[ 0.36103462, -1.28930935, 1.34586369, -0.57300728],
[-1.42711933, -0.11832827, -0.58038295, -1.56806583]])
y_train = np.sum(np.abs(X_train), axis=1)
parameters = {
'n_neighbors': [1, 2, 4],
'metrics': ['euclidean', 'cosine'],
'weights': ['uniform', 'distance'],
'normalizers': [(None, 'None')]
}
folds = kfold_split(10, 3)
out = knn_cv_score(X_train, y_train, parameters, r2_score, folds, neighbors.KNeighborsRegressor)
answer = {
('None', 1, 'euclidean', 'uniform'): -3.8869140469579033,
('None', 1, 'euclidean', 'distance'): -3.8869140469579033,
('None', 1, 'cosine', 'uniform'): -3.8967543637841557,
('None', 1, 'cosine', 'distance'): -3.8967543637841557,
('None', 2, 'euclidean', 'uniform'): -2.8537893891104353,
('None', 2, 'euclidean', 'distance'): -2.8723718210868676,
('None', 2, 'cosine', 'uniform'): -0.9110922868244854,
('None', 2, 'cosine', 'distance'): -1.2935713889809644,
('None', 4, 'euclidean', 'uniform'): -1.0722930212962776,
('None', 4, 'euclidean', 'distance'): -1.291339953080277,
('None', 4, 'cosine', 'uniform'): 0.010193326582544423,
('None', 4, 'cosine', 'distance'): -0.38359677639174855
}
assert type(out) == dict
assert len(out) == len(answer)
for key in answer:
assert_allclose(answer[key], out[key])
def test_cv_6():
X_train = np.array([[ 0.62069296, -0.07097426, 0.65172896, -1.14620331],
[ 2.03347616, 0.32524614, -0.71941433, -0.30789854],
[ 0.17100377, 1.63120292, 1.34284446, -2.16397238],
[-1.65370417, 0.62499229, -0.50217293, 2.07813591],
[ 0.84667916, 0.25458428, 0.14720704, -0.18668345],
[ 0.43833344, -1.40348048, -1.37944118, 0.19192659],
[ 0.97229574, -0.54606276, -0.09855294, 1.28961291],
[ 0.25355626, -1.72816511, 0.084554 , -2.14256875],
[ 0.36103462, -1.28930935, 1.34586369, -0.57300728],
[-1.42711933, -0.11832827, -0.58038295, -1.56806583]])
y_train = np.sum(np.abs(X_train), axis=1)
scaler = MinMaxScaler()
parameters = {
'n_neighbors': [1, 2, 4],
'metrics': ['euclidean', 'cosine'],
'weights': ['uniform', 'distance'],
'normalizers': [(scaler, 'MinMaxScaler')]
}
folds = kfold_split(10, 3)
out = knn_cv_score(X_train, y_train, parameters, r2_score, folds, neighbors.KNeighborsRegressor)
answer = {
('MinMaxScaler', 1, 'euclidean', 'uniform'): -3.886914104013526,
('MinMaxScaler', 1, 'euclidean', 'distance'): -3.886914104013526,
('MinMaxScaler', 1, 'cosine', 'uniform'): -3.339427669385479,
('MinMaxScaler', 1, 'cosine', 'distance'): -3.339427669385479,
('MinMaxScaler', 2, 'euclidean', 'uniform'): -2.821522070818421,
('MinMaxScaler', 2, 'euclidean', 'distance'): -2.909515284414977,
('MinMaxScaler', 2, 'cosine', 'uniform'): -3.0373126577073877,
('MinMaxScaler', 2, 'cosine', 'distance'): -2.7197802024893374,
('MinMaxScaler', 4, 'euclidean', 'uniform'): -1.229118435031323,
('MinMaxScaler', 4, 'euclidean', 'distance'): -1.4848798788742938,
('MinMaxScaler', 4, 'cosine', 'uniform'): -0.3586698577110674,
('MinMaxScaler', 4, 'cosine', 'distance'): -0.7914850319051477
}
assert type(out) == dict
assert len(out) == len(answer)
for key in answer:
assert_allclose(answer[key], out[key])
@@ -0,0 +1,21 @@
catboost==1.2.8
gdown==5.2.0
h5py==3.14.0
hyperopt==0.2.7
ipympl==0.9.7
ipywidgets==7.7.1
lightgbm==4.6.0
matplotlib-inline==0.1.7
matplotlib==3.10.0
pandas==2.2.2
pep8==1.7.1
plotly==5.24.1
pycodestyle==2.14.0
pytest==8.4.1
scikit-image==0.25.2
scikit-learn==1.6.1
scipy==1.16.1
seaborn==0.13.2
tqdm==4.67.1
umap-learn==0.5.9.post2
xgboost==3.0.4
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
from json import load, dumps
from glob import glob
from os import environ
from os.path import join
from sys import argv, exit
def run_single_test(data_dir, output_dir):
from pytest import main
exit(main(['-vv', '-p', 'no:cacheprovider', join(data_dir, 'test.py')]))
def check_test(data_dir):
pass
def grade(data_path):
results = load(open(join(data_path, 'results.json')))
max_mark = 3
grade_mapping = [3]
total_grade = 0
ok_count = 0
for result, grade in zip(results, grade_mapping):
if result['status'] == 'Ok':
total_grade += grade
ok_count += 1
total_count = len(results)
description = '%02d/%02d' % (ok_count, total_count)
mark = total_grade / sum(grade_mapping) * max_mark
res = {'description': description, 'mark': mark}
if environ.get('CHECKER'):
print(dumps(res))
return res
if __name__ == '__main__':
if environ.get('CHECKER'):
# Script is running in testing system
if len(argv) != 4:
print('Usage: %s mode data_dir output_dir' % argv[0])
exit(0)
mode = argv[1]
data_dir = argv[2]
output_dir = argv[3]
if mode == 'run_single_test':
run_single_test(data_dir, output_dir)
elif mode == 'check_test':
check_test(data_dir)
elif mode == 'grade':
grade(data_dir)
else:
# Script is running locally
if len(argv) != 3:
print(f'Usage: {argv[0]} test/unittest test_name')
exit(0)
mode = argv[1]
test_name = argv[2]
test_dir = glob(f'public_tests/[0-9][0-9]_{mode}_{test_name}_input')
if not test_dir:
print('Test not found')
exit(0)
from pytest import main
exit(main(['-vv', join(test_dir[0], 'test.py')]))
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
catboost==1.2.8
gdown==5.2.0
h5py==3.14.0
hyperopt==0.2.7
ipympl==0.9.7
ipywidgets==7.7.1
lightgbm==4.6.0
matplotlib-inline==0.1.7
matplotlib==3.10.0
pandas==2.2.2
pep8==1.7.1
plotly==5.24.1
pycodestyle==2.14.0
pytest==8.4.1
scikit-image==0.25.2
scikit-learn==1.6.1
scipy==1.16.1
seaborn==0.13.2
tqdm==4.67.1
umap-learn==0.5.9.post2
xgboost==3.0.4
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,22 @@
catboost==1.2.8
gdown==5.2.0
h5py==3.14.0
hyperopt==0.2.7
ipympl==0.9.7
ipywidgets==7.7.1
lightgbm==4.6.0
matplotlib-inline==0.1.7
matplotlib==3.10.0
numpy
pandas==2.2.2
pep8==1.7.1
plotly==5.24.1
pycodestyle==2.14.0
pytest==8.4.1
scikit-image==0.25.2
scikit-learn==1.6.1
scipy==1.16.1
seaborn==0.13.2
tqdm==4.67.1
umap-learn==0.5.9.post2
xgboost==3.0.4
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,22 @@
catboost==1.2.8
gdown==5.2.0
h5py==3.14.0
hyperopt==0.2.7
ipympl==0.9.7
ipywidgets==7.7.1
lightgbm==4.6.0
matplotlib-inline==0.1.7
matplotlib==3.10.0
numpy
pandas==2.2.2
pep8==1.7.1
plotly==5.24.1
pycodestyle==2.14.0
pytest==8.4.1
scikit-image==0.25.2
scikit-learn==1.6.1
scipy==1.16.1
seaborn==0.13.2
tqdm==4.67.1
umap-learn==0.5.9.post2
xgboost==3.0.4
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,22 @@
catboost==1.2.8
gdown==5.2.0
h5py==3.14.0
hyperopt==0.2.7
ipympl==0.9.7
ipywidgets==7.7.1
lightgbm==4.6.0
matplotlib-inline==0.1.7
matplotlib==3.10.0
numpy
pandas==2.2.2
pep8==1.7.1
plotly==5.24.1
pycodestyle==2.14.0
pytest==8.4.1
scikit-image==0.25.2
scikit-learn==1.6.1
scipy==1.16.1
seaborn==0.13.2
tqdm==4.67.1
umap-learn==0.5.9.post2
xgboost==3.0.4
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
from task15 import hello
import pytest
# task 1
@pytest.mark.parametrize(
"arg,res",
[
('', 'Hello!'),
('Masha', 'Hello, Masha!'),
(' ', 'Hello, !'),
('r', 'Hello, r!'),
('123', 'Hello, 123!'),
('I love machine learning', 'Hello, I love machine learning!')
]
)
def test_one_argument(arg, res):
assert hello(arg) == res
def test_no_arguments():
assert hello() == 'Hello!'
+36
View File
@@ -0,0 +1,36 @@
from task15 import int_to_roman
import pytest
@pytest.mark.parametrize(
"num,ans",
[
[1, 'I'],
[2, 'II'],
[3, 'III'],
[4, 'IV'],
[5, 'V'],
[6, 'VI'],
[7, 'VII'],
[9, "IX"],
[10, 'X'],
[20, 'XX'],
[50, 'L'],
[54, 'LIV'],
[90, "XC"],
[100, 'C'],
[199, "CXCIX"],
[328, "CCCXXVIII"],
[400, "CD"],
[500, 'D'],
[754, "DCCLIV"],
[888, "DCCCLXXXVIII"],
[973, "CMLXXIII"],
[1000, 'M'],
[1996, 'MCMXCVI'],
[2143, "MMCXLIII"]
]
)
def test_int_to_roman(num, ans):
assert int_to_roman(num) == ans
+22
View File
@@ -0,0 +1,22 @@
from task15 import longest_common_prefix
import pytest
@pytest.mark.parametrize(
"arg,res",
[
[["flower","flow","flight"], "fl"],
[[" flower"," flow"," flight", "flight "], "fl"],
[["dog","racecar","car"], ""],
[["c","cc","ccc"], "c"],
[[""," "," "], ""],
[[" "," "," "], ""],
[["123"," 1 23","12 3"], "1"],
[["1" for _ in range(100)], "1"],
[["23" + str(i) for i in range(100)], "23"],
[[" ML;", "\t\t\tML", "\n \tML"], "ML"],
[[], ""]
]
)
def test_prefix(arg, res):
assert longest_common_prefix(arg) == res
+34
View File
@@ -0,0 +1,34 @@
from task15 import BankCard
import pytest
# task 4
def test_bank_card():
a = BankCard(100, 2)
assert a.total_sum == 100
assert a.balance_limit == 2
assert a.__str__() == "To learn the balance call balance."
a(50)
assert a.total_sum == 50
assert a.balance == 50
assert a.balance_limit == 1
try:
a(50)
except ValueError:
pass
assert a.total_sum == 0
a.put(30)
assert a.balance == 30
try:
a.balance
except ValueError:
pass
b = BankCard(50)
for i in range(100):
assert b.balance == 50
c = BankCard(300, 2)
d = a + c
assert d.total_sum == 330
assert d.balance_limit == 2
+16
View File
@@ -0,0 +1,16 @@
from task15 import primes
import itertools
import pytest
@pytest.mark.parametrize(
"arg,res",
[
[list(itertools.takewhile(lambda x : x <= 31, primes())), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]],
[list(itertools.takewhile(lambda x : x <= 35, primes())), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]],
[list(itertools.takewhile(lambda x : x <= 1, primes())), []],
[list(itertools.takewhile(lambda x : x <= 700, primes())), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691]]
]
)
def test_one_argument(arg, res):
assert arg == res
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
from json import load, dumps
from glob import glob
from os import environ
from os.path import join
from sys import argv, exit
def run_single_test(data_dir, output_dir):
from pytest import main
exit(main(['-vv', '-p', 'no:cacheprovider', join(data_dir, 'test.py')]))
def check_test(data_dir):
pass
def grade(data_path):
results = load(open(join(data_path, 'results.json')))
max_mark = 5
grade_mapping = [1, 1, 1, 1, 1]
total_grade = 0
ok_count = 0
for result, grade in zip(results, grade_mapping):
if result['status'] == 'Ok':
total_grade += grade
ok_count += 1
total_count = len(results)
description = '%02d/%02d' % (ok_count, total_count)
mark = total_grade / sum(grade_mapping) * max_mark
res = {'description': description, 'mark': mark}
if environ.get('CHECKER'):
print(dumps(res))
return res
if __name__ == '__main__':
if environ.get('CHECKER'):
# Script is running in testing system
if len(argv) != 4:
print('Usage: %s mode data_dir output_dir' % argv[0])
exit(0)
mode = argv[1]
data_dir = argv[2]
output_dir = argv[3]
if mode == 'run_single_test':
run_single_test(data_dir, output_dir)
elif mode == 'check_test':
check_test(data_dir)
elif mode == 'grade':
grade(data_dir)
else:
# Script is running locally
if len(argv) != 3:
print(f'Usage: {argv[0]} test/unittest test_name')
exit(0)
mode = argv[1]
test_name = argv[2]
test_dir = glob(f'python_intro_public_test/[0-9][0-9]_{mode}_{test_name}_input')
if not test_dir:
print('Test not found')
exit(0)
from pytest import main
exit(main(['-vv', join(test_dir[0], 'test.py')]))
+112
View File
@@ -0,0 +1,112 @@
def hello(x=None) -> str:
return f"Hello{', ' + str(x) if x else ''}!"
def int_to_roman(x: int) -> str:
int_roman = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
res = ""
for n, rom in int_roman:
while x >= n:
res += rom
x -= n
return res
def longest_common_prefix(x: list[str]) -> str:
if not x or not x[0]:
return ""
prefix = x[0].strip()
break_flag = False
i = 0
while i < len(prefix):
for s in x:
s = s.strip()
if i >= len(s) or s[i] != prefix[i]:
break_flag = True
break
if break_flag:
break
i += 1
return prefix[:i]
class BankCard:
def __init__(self, total_sum: int, balance_limit: int = -1) -> None:
self.total_sum = total_sum
self.balance_limit = balance_limit
def put(self, sum_put: int):
self.total_sum += sum_put
print(f"You put {sum_put} dollars.")
return self
@property
def balance(self) -> int:
if self.balance_limit == 0:
raise ValueError("Balance check limits exceeded.")
self.balance_limit -= 1
return self.total_sum
def __add__(self, other):
return type(self)(
self.total_sum + other.total_sum,
(
max(self.balance_limit, other.balance_limit)
if self.balance_limit != -1 and other.balance_limit != -1
else -1
),
)
def __str__(self) -> str:
return "To learn the balance call balance."
def __call__(self, sum_spent: int) -> None:
if self.total_sum < sum_spent:
raise ValueError(f"Not enough money to spend {sum_spent} dollars.")
print(f"You spent {sum_spent} dollars")
self.total_sum -= sum_spent
return
def primes():
num = 2
while True:
prime = True
for i in range(2, int(num**0.5) + 1):
if not num % i:
prime = False
break
if prime:
yield num
num += 1
+115
View File
@@ -0,0 +1,115 @@
def hello(x=None) -> str:
s = "Hello"
if x:
s += f", {x}"
return s + "!"
def int_to_roman(x: int) -> str:
match = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
lst = []
for num, text in match:
while x >= num:
x -= num
lst.append(text)
return "".join(lst)
def longest_common_prefix(x: list[str]) -> str:
if not x:
return ""
s = x[0].strip()
ind = 0
flag = False
while ind < len(s):
for word in x:
word = word.strip()
if len(word) <= ind or word[ind] != s[ind]:
flag = True
break
if flag:
break
ind += 1
if ind == -1:
return ""
return s[:ind]
class BankCard:
def __init__(self, total_sum: int, balance_limit: int = -1) -> None:
self.total_sum = total_sum
self.balance_limit = balance_limit
@property
def balance(self) -> int:
if self.balance_limit == 0:
raise ValueError("Balance check limits exceeded.")
self.balance_limit -= 1
return self.total_sum
def put(self, sum_put: int):
self.total_sum += sum_put
print(f"You put {sum_put} dollars.")
return self
def __add__(self, other):
if self.balance_limit == -1 or other.balance_limit == -1:
new_balance_limit = -1
else:
new_balance_limit = max(self.balance_limit, other.balance_limit)
return type(self)(self.total_sum + other.total_sum, new_balance_limit)
def __call__(self, sum_spent: int) -> None:
if self.total_sum < sum_spent:
raise ValueError(f"Not enough money to spend sum_spent dollars.")
self.total_sum -= sum_spent
print(f"You spent {sum_spent} dollars")
return
def __str__(self) -> str:
return "To learn the balance call balance."
def primes():
pr = 2
while True:
flag = False
for n in range(2, int(pr**0.5) + 1):
if pr % n == 0:
flag = True
break
if not flag:
yield pr
pr += 1
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,6 @@
a 2
aa 2
abc 2
ac 1
bcd 1
@@ -0,0 +1,5 @@
a 2
aa 2
abc 2
ac 1
bcd 1
@@ -0,0 +1,6 @@
a 2
aa 2
abc 2
ac 1
bcd 1
@@ -0,0 +1 @@
a aa abC aa ac abc bcd a
@@ -0,0 +1,2 @@
a 3
@@ -0,0 +1 @@
a 3
@@ -0,0 +1,2 @@
a 3
@@ -0,0 +1 @@
a A a
@@ -0,0 +1,10 @@
a 1
aaa 1
b 4
c 5
cc 1
ccc 1
d 2
f 1
r 1
@@ -0,0 +1,9 @@
a 1
aaa 1
b 4
c 5
cc 1
ccc 1
d 2
f 1
r 1
@@ -0,0 +1,10 @@
a 1
aaa 1
b 4
c 5
cc 1
ccc 1
d 2
f 1
r 1
@@ -0,0 +1 @@
c c f d aaA a c d r c ccc cC c b b b b
@@ -0,0 +1 @@
[{"status": "Ok"}, {"status": "Ok"}, {"status": "Ok"}]
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
from json import load, dump, dumps
from glob import glob
from os import environ
from os.path import join
from sys import argv, exit
import os
import re
def run_single_test(data_dir, output_dir):
from task6 import check
with open(join(data_dir, 'input.txt')) as f:
check(f.read().strip(), join(output_dir, 'file.txt'))
def check_test(data_dir):
output_dir = os.path.join(data_dir, 'output')
gt_dir = os.path.join(data_dir, 'gt')
with open(join(output_dir, 'file.txt')) as f:
output = f.read().strip()
with open(join(gt_dir, 'file.txt')) as f:
gt = f.read().strip()
if output == gt:
res = f'Ok'
else:
res = f'Files are not the same'
if environ.get('CHECKER'):
print(res)
return res
def grade(data_dir):
results = load(open(join(data_dir, 'results.json')))
ok_count = 0
for result in results:
if result['status'] == 'Ok':
ok_count += 1
if ok_count == 3:
mark = 2
else:
mark = 0
total_count = len(results)
description = '%02d/%02d' % (ok_count, total_count)
res = {'description': description, 'mark': mark}
if environ.get('CHECKER'):
print(dumps(res))
return res
if __name__ == '__main__':
if environ.get('CHECKER'):
# Script is running in testing system
if len(argv) != 4:
print('Usage: %s mode data_dir output_dir' % argv[0])
exit(0)
mode, data_dir, output_dir = argv[1], argv[2], argv[3]
if mode == 'run_single_test':
run_single_test(data_dir, output_dir)
elif mode == 'check_test':
check_test(data_dir)
elif mode == 'grade':
grade(data_dir)
else:
# Script is running locally
if len(argv) != 2:
print(f'Usage: {argv[0]} tests_dir')
exit(0)
from glob import glob
from json import dump
from re import sub
from time import time
from traceback import format_exc
from os import makedirs
from os.path import basename, exists
from shutil import copytree
tests_dir = argv[1]
results = []
for input_dir in sorted(glob(join(tests_dir, '[0-9][0-9]_*_input'))):
output_dir = sub('input$', 'check', input_dir)
run_output_dir = join(output_dir, 'output')
makedirs(run_output_dir, exist_ok=True)
gt_src = sub('input$', 'gt', input_dir)
gt_dst = join(output_dir, 'gt')
if not exists(gt_dst):
copytree(gt_src, gt_dst)
try:
start = time()
run_single_test(input_dir, run_output_dir)
end = time()
running_time = end - start
except:
status = 'Runtime error'
traceback = format_exc()
else:
try:
status = check_test(output_dir)
except:
status = 'Checker error'
traceback = format_exc()
test_num = basename(input_dir)[:2]
if status == 'Runtime error' or status == 'Checker error':
print(test_num, status, '\n', traceback)
results.append({'status': status})
else:
results.append({'status': status})
dump(results, open(join(tests_dir, 'results.json'), 'w'))
res = grade(tests_dir)
print('Mark:', res['mark'], res['description'])
+11
View File
@@ -0,0 +1,11 @@
import collections
def check(line, name):
cnt = collections.Counter(line.lower().split())
with open(name, "w") as f:
for word in sorted(cnt):
f.write(f"{word} {cnt[word]}\n")
return
+12
View File
@@ -0,0 +1,12 @@
from collections import Counter
def check(line, file):
words = line.lower().split(" ")
counter = Counter(words)
with open(file, "w") as file:
for i in sorted(counter):
file.write(f"{i} {counter[i]}\n")
return
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
from task7 import find_modified_max_argmax
print(find_modified_max_argmax([1, 3, 4, 4.5], lambda x: x**2)) # (16, 2)
print(find_modified_max_argmax(["a", 4.5], lambda x: x*10)) # ()
+4
View File
@@ -0,0 +1,4 @@
def find_modified_max_argmax(L, f):
L = [f(x) for x in L if type(x) == int]
return L and (max(L), L.index(max(L))) or ()
+4
View File
@@ -0,0 +1,4 @@
def find_modified_max_argmax(L, f):
L = [f(x) for x in L if type(x) == int]
return (max(L), L.index(max(L))) if L else ()
BIN
View File
Binary file not shown.
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,67 @@
import numpy as np
from numpy.testing import assert_allclose
from scalers import StandardScaler, MinMaxScaler
def test_scalers_0():
with open('scalers.py', 'r') as file:
lines = ' '.join(file.readlines())
assert 'import numpy' in lines
assert 'import typing' in lines
assert lines.count('import') == 2
assert 'sklearn' not in lines
def test_scalers_1():
X_1 = np.random.uniform(-10, 20, (10, 20))
scaler = StandardScaler()
scaler.fit(X_1)
X_2 = scaler.transform(X_1)
assert type(X_2) == np.ndarray
assert_allclose(np.mean(X_2, axis=0), np.zeros(20), rtol=1e-05, atol=1e-08)
assert_allclose(np.std(X_2, axis=0), np.ones(20), rtol=1e-05, atol=1e-08)
def test_scalers_2():
X_1 = np.random.uniform(-10, 20, (10, 20))
scaler = MinMaxScaler()
scaler.fit(X_1)
X_2 = scaler.transform(X_1)
assert type(X_2) == np.ndarray
assert_allclose(np.min(X_2, axis=0), np.zeros(20), rtol=1e-05, atol=1e-08)
assert_allclose(np.max(X_2, axis=0), np.ones(20), rtol=1e-05, atol=1e-08)
def test_scalers_3():
X_1 = np.array([[0, 1, 0], [1, 1, 1], [0.3, 0.25, 0.5], [-0.5, -1, 4]])
X_2 = np.array([[0, 1, 0], [1, 1, 1], [0.3, 0.25, 0.5], [-0.5, -1, 4], [0, 0, 0], [2, -1, 0.5]])
scaler = StandardScaler()
scaler.fit(X_1)
X_3 = scaler.transform(X_2)
answer = np.array([[-0.36822985, 0.84119102, -0.88354126],
[ 1.47291939, 0.84119102, -0.2409658 ],
[ 0.18411492, -0.07647191, -0.56225353],
[-1.28880447, -1.60591014, 1.68676059],
[-0.36822985, -0.38235956, -0.88354126],
[ 3.31406862, -1.60591014, -0.56225353]])
assert type(X_3) == np.ndarray
assert_allclose(X_3, answer, rtol=1e-05, atol=1e-08)
def test_scalers_4():
X_1 = np.array([[0, 1, 0], [1, 1, 1], [0.3, 0.25, 0.5], [-0.5, -1, 4]])
X_2 = np.array([[0, 1, 0], [1, 1, 1], [0.3, 0.25, 0.5], [-0.5, -1, 4], [0, 0, 0], [2, -1, 0.5]])
scaler = MinMaxScaler()
scaler.fit(X_1)
X_3 = scaler.transform(X_2)
answer = np.array([[0.33333333, 1. , 0. ],
[1. , 1. , 0.25 ],
[0.53333333, 0.625 , 0.125 ],
[0. , 0. , 1. ],
[0.33333333, 0.5 , 0. ],
[1.66666667, 0. , 0.125 ]])
assert type(X_3) == np.ndarray
assert_allclose(X_3, answer, rtol=1e-05, atol=1e-08)
@@ -0,0 +1,22 @@
catboost==1.2.8
gdown==5.2.0
h5py==3.14.0
hyperopt==0.2.7
ipympl==0.9.7
ipywidgets==7.7.1
lightgbm==4.6.0
matplotlib-inline==0.1.7
matplotlib==3.10.0
numpy
pandas==2.2.2
pep8==1.7.1
plotly==5.24.1
pycodestyle==2.14.0
pytest==8.4.1
scikit-image==0.25.2
scikit-learn==1.6.1
scipy==1.16.1
seaborn==0.13.2
tqdm==4.67.1
umap-learn==0.5.9.post2
xgboost==3.0.4
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
from json import load, dumps
from glob import glob
from os import environ
from os.path import join
from sys import argv, exit
def run_single_test(data_dir, output_dir):
from pytest import main
exit(main(['-vv', '-p', 'no:cacheprovider', join(data_dir, 'test.py')]))
def check_test(data_dir):
pass
def grade(data_path):
results = load(open(join(data_path, 'results.json')))
max_mark = 4
grade_mapping = [4]
total_grade = 0
ok_count = 0
for result, grade in zip(results, grade_mapping):
if result['status'] == 'Ok':
total_grade += grade
ok_count += 1
total_count = len(results)
description = '%02d/%02d' % (ok_count, total_count)
mark = total_grade / sum(grade_mapping) * max_mark
res = {'description': description, 'mark': mark}
if environ.get('CHECKER'):
print(dumps(res))
return res
if __name__ == '__main__':
if environ.get('CHECKER'):
# Script is running in testing system
if len(argv) != 4:
print('Usage: %s mode data_dir output_dir' % argv[0])
exit(0)
mode = argv[1]
data_dir = argv[2]
output_dir = argv[3]
if mode == 'run_single_test':
run_single_test(data_dir, output_dir)
elif mode == 'check_test':
check_test(data_dir)
elif mode == 'grade':
grade(data_dir)
else:
# Script is running locally
if len(argv) != 3:
print(f'Usage: {argv[0]} test/unittest test_name')
exit(0)
mode = argv[1]
test_name = argv[2]
test_dir = glob(f'public_tests/[0-9][0-9]_{mode}_{test_name}_input')
if not test_dir:
print('Test not found')
exit(0)
from pytest import main
exit(main(['-vv', join(test_dir[0], 'test.py')]))
+32
View File
@@ -0,0 +1,32 @@
import numpy as np
import typing
class MinMaxScaler:
def __init__(self):
self.min_vals = None
self.max_vals = None
def fit(self, data: np.ndarray) -> None:
self.min_vals = np.min(data, axis=0)
self.max_vals = np.max(data, axis=0)
return
def transform(self, data: np.ndarray) -> np.ndarray:
return (data - self.min_vals) / (self.max_vals - self.min_vals)
class StandardScaler:
def __init__(self):
self.mean_vals = None
self.std_vals = None
def fit(self, data: np.ndarray) -> None:
self.mean_vals = np.mean(data, axis=0)
self.std_vals = np.std(data, axis=0)
return
def transform(self, data: np.ndarray) -> np.ndarray:
return (data - self.mean_vals) / self.std_vals