Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions .github/workflows/github-actions-testing.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
name: Testing the Python code

on:
push:
branches:
- main
on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
build:
Expand Down
39 changes: 39 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# Virtual environments
.env
.venv
env/
venv/

# IDEs
.vscode/
.idea/

# Pytest
.pytest_cache/
.coverage
htmlcov/

# Jupyter Notebook checkpoints
.ipynb_checkpoints/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Fenrir.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
8 changes: 8 additions & 0 deletions data/data.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
- Иванов Иван Иванович
математика 67
литература 100
программирование 91
- Петров Петр Петрович
математика 78
химия 87
социология 61
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pytest
pycodestyle
pycodestyle
pyyaml
26 changes: 26 additions & 0 deletions src/QuartileCalculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
from typing import Dict, List
from statistics import quantiles


class QuartileCalculator:
"""
Принимает на вход словарь { ФИО: рейтинг } и позволяет получить студентов,
попавших в заданную квартиль. Для 2-й квартиль используем правило:
q1 < rating <= q2 (верхняя граница включительно).
"""

def __init__(self, ratings: Dict[str, float]) -> None:
self.ratings = ratings

def second_quartile_students(self) -> List[str]:
values = list(self.ratings.values())
if not values:
return []

# Получим границы квартилей (Q1, Q2, Q3)
q1, q2, _q3 = quantiles(values, n=4, method="inclusive")

return sorted(
[name for name, r in self.ratings.items() if (r > q1 and r <= q2)]
)
43 changes: 43 additions & 0 deletions src/YamlDataReader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
from typing import Dict, List, Tuple
import yaml # type: ignore
from Types import DataType
from DataReader import DataReader


class YamlDataReader(DataReader):
"""
Ожидаемый формат YAML (список студентов):
- Иванов Иван Иванович:
математика: 67
литература: 100
программирование: 91
- Петров Петр Петрович:
математика: 78
химия: 87
социология: 61
"""

def __init__(self) -> None:
self.students: DataType = {}

def read(self, path: str) -> DataType:
with open(path, "r", encoding="utf-8") as f:
loaded = yaml.safe_load(f)

# loaded — это список словарей { "ФИО": { "предмет": балл, ... } }
self.students = {}
if not isinstance(loaded, list):
return self.students

for item in loaded:
if not isinstance(item, dict):
continue
for full_name, subjects in item.items():
subj_list: List[Tuple[str, int]] = []
if isinstance(subjects, dict):
for subj, score in subjects.items():
subj_list.append((str(subj), int(score)))
self.students[str(full_name)] = subj_list

return self.students
43 changes: 29 additions & 14 deletions src/main.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,43 @@
# -*- coding: utf-8 -*-
import argparse
import sys

from CalcRating import CalcRating
from TextDataReader import TextDataReader
from YamlDataReader import YamlDataReader
from QuartileCalculator import QuartileCalculator


def get_path_from_arguments(args) -> str:
def get_path_from_arguments(args) -> tuple[str, bool]:
parser = argparse.ArgumentParser(description="Path to datafile")
parser.add_argument("-p", dest="path", type=str, required=True,
help="Path to datafile")
args = parser.parse_args(args)
return args.path


def main():
path = get_path_from_arguments(sys.argv[1:])

reader = TextDataReader()
parser.add_argument(
"-p",
dest="path",
type=str,
required=True,
help="Path to datafile"
)
parser.add_argument(
"--yaml",
action="store_true",
help="Use YAML reader"
)
parsed = parser.parse_args(args)
return parsed.path, parsed.yaml


def main() -> None:
path, use_yaml = get_path_from_arguments(sys.argv[1:])

reader = YamlDataReader() if use_yaml else TextDataReader()
students = reader.read(path)
print("Students: ", students)
print("Students:", students)

rating = CalcRating(students).calc()
print("Rating: ", rating)
print("Rating:", rating)

# Вариант 8: вывести студентов второй квартиль
q = QuartileCalculator(rating)
print("2nd quartile students:", q.second_quartile_students())


if __name__ == "__main__":
Expand Down
14 changes: 8 additions & 6 deletions test/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@


@pytest.fixture()
def correct_arguments_string() -> tuple[list[str], str]:
return ["-p", "/home/user/file.txt"], "/home/user/file.txt"
def correct_arguments_string() -> tuple[list[str], tuple[str, bool]]:
return ["-p", "/home/user/file.txt"], ("/home/user/file.txt", False)


@pytest.fixture()
Expand All @@ -14,13 +14,15 @@ def noncorrect_arguments_string() -> list[str]:


def test_get_path_from_correct_arguments(
correct_arguments_string: tuple[list[str], str]) -> None:
path = get_path_from_arguments(correct_arguments_string[0])
assert path == correct_arguments_string[1]
correct_arguments_string: tuple[list[str], tuple[str, bool]]
) -> None:
path, is_yaml = get_path_from_arguments(correct_arguments_string[0])
assert (path, is_yaml) == correct_arguments_string[1]


def test_get_path_from_noncorrect_arguments(
noncorrect_arguments_string: list[str]) -> None:
noncorrect_arguments_string: list[str]
) -> None:
with pytest.raises(SystemExit) as e:
get_path_from_arguments(noncorrect_arguments_string[0])
assert e.type == SystemExit
18 changes: 18 additions & 0 deletions test/test_QuartileCalculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
from src.QuartileCalculator import QuartileCalculator
from src.CalcRating import CalcRating
from src.Types import DataType


def test_second_quartile_students() -> None:
# Дадим 4 студента, чтобы квартильные границы были корректны
data: DataType = {
"A": [("s1", 60), ("s2", 60)], # среднее = 60
"B": [("s1", 70), ("s2", 70)], # среднее = 70 -> Q2
"C": [("s1", 80), ("s2", 80)], # среднее = 80 -> Q3
"D": [("s1", 90), ("s2", 90)], # среднее = 90 -> Q4
}
ratings = CalcRating(data).calc()
q = QuartileCalculator(ratings)
# Во вторую квартиль попадают значения (q1, q2] — здесь это только B
assert q.second_quartile_students() == ["B"]
49 changes: 49 additions & 0 deletions test/test_YamlDataReader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
import pytest
from src.Types import DataType
from src.YamlDataReader import YamlDataReader


class TestYamlDataReader:
@pytest.fixture()
def yaml_text_and_data(self) -> tuple[str, DataType]:
yaml_text = (
"- Иванов Иван Иванович:\n"
" математика: 67\n"
" литература: 100\n"
" программирование: 91\n"
"- Петров Петр Петрович:\n"
" математика: 78\n"
" химия: 87\n"
" социология: 61\n"
)
expected: DataType = {
"Иванов Иван Иванович": [
("математика", 67),
("литература", 100),
("программирование", 91),
],
"Петров Петр Петрович": [
("математика", 78),
("химия", 87),
("социология", 61),
],
}
return yaml_text, expected

@pytest.fixture()
def filepath_and_data(
self,
yaml_text_and_data: tuple[str, DataType],
tmpdir
) -> tuple[str, DataType]:
p = tmpdir.mkdir("datadir").join("students.yaml")
p.write_text(yaml_text_and_data[0], encoding="utf-8")
return str(p), yaml_text_and_data[1]

def test_read_yaml(
self,
filepath_and_data: tuple[str, DataType]
) -> None:
content = YamlDataReader().read(filepath_and_data[0])
assert content == filepath_and_data[1]
28 changes: 28 additions & 0 deletions test/test_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
from src.main import get_path_from_arguments
import pytest


@pytest.fixture()
def correct_arguments_string() -> tuple[list[str], tuple[str, bool]]:
return ["-p", "/home/user/file.txt"], ("/home/user/file.txt", False)


@pytest.fixture()
def noncorrect_arguments_string() -> list[str]:
return ["/home/user/file.txt"]


def test_get_path_from_correct_arguments(
correct_arguments_string: tuple[list[str], tuple[str, bool]]
) -> None:
path, is_yaml = get_path_from_arguments(correct_arguments_string[0])
assert (path, is_yaml) == correct_arguments_string[1]


def test_get_path_from_noncorrect_arguments(
noncorrect_arguments_string: list[str]
) -> None:
with pytest.raises(SystemExit) as e:
get_path_from_arguments(noncorrect_arguments_string[0])
assert e.type == SystemExit