Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mukhin Dmitry test task4 #18

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,26 @@ CodeKiller777

## Автор решения

__Мухин Дмитрий Владимирович__

## Описание реализации

Решение задачи представляет собой консольное приложение, написанное на языке программирования Python.

Алгоритм решения задачи:

1. Считывание данных из файла `commits.txt`.
2. Подсчет количества коммитов для каждого контрибьютера с использованием словаря. Ключом словаря является имя контрибьютера, значением - количество его коммитов.
3. Поиск 3-х самых активных контрибьютеров с помощью минимальной кучи.
Она выбрана для решения задачи, так как позволяет искать трех лучших контрибьютеров за O(n),
где n - количество контрибьютеров. При использовании сортировки сложность составила бы O(nlogn).
4. Формирование списка имен контрибьютеров в нужном порядке.
5. Запись результатов в файл `result.txt`.

## Инструкция по сборке и запуску решения

- Для работы программы необходим интерпретатор Python 3. Предпочтительно использовать последнюю версию.
- Скачайте файлы `main.py` и `validators.py` из репозитория.
- Поместите файл `commits.txt` в папку с файлом `main.py`.
- Запустите программу, выполнив команду `python main.py` в этой директории или запустив файл `main.py` в вашей среде разработки.
- После выполнения программы в папке с файлом `commits.txt` появится файл `result.txt` с результатами.
10 changes: 10 additions & 0 deletions commits.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
AIvanov 25ec001 2024-04-24T13:56:39
AKalinina 3b6ef45 2024-04-24T14:01:22
AKalinina 3b6ef45 2024-04-24T14:01:22
AKalinina 3b6ef45 2024-04-24T14:01:22
CodeKiller777 4f8c1d2 2024-04-24T14:05:45
AIvanov 25ec001 2024-04-24T13:56:39
AKalinina 3b6ef45 2024-04-24T14:01:22
CodeKiller777 4f8c1d2 2024-04-24T14:05:45
CodeKiller777 4f8c1d2 2024-04-24T14:05:45
AIvanov 25ec001 2024-04-24T13:56:39
55 changes: 55 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import heapq
from validators import validate_commit


def read_commits(input_file: str) -> dict:
"""
A function to read the commits from a file.
:return: a dictionary with contributors and their commits count.
"""
commits = {}
with open(input_file, 'r') as file:
for line in file:
line = line.strip()
if validate_commit(line):
contributor = line.split()[0]
commits[contributor] = commits.get(contributor, 0) + 1
return commits


def write_winners(winners: list, output_file: str) -> None:
""" A function to write the winners to a file. """
with open(output_file, 'w') as file:
for winner in winners:
file.write(winner + '\n')


def find_winners(commits: dict, winners_count: int) -> list:
"""
A function to find the most active contributors.
:return: a list of the most active contributors in descending order.
"""
winners_heap = []
for contributor, commits_count in commits.items():
# Collect the necessary number of winners.
if len(winners_heap) < winners_count:
heapq.heappush(winners_heap, (commits_count, contributor))
else:
# Replace the contributor with the least commits count if the current contributor has more commits.
if commits_count > winners_heap[0][0]:
heapq.heappop(winners_heap)
heapq.heappush(winners_heap, (commits_count, contributor))

sorted_winners = sorted(winners_heap, key=lambda x: (x[0]))
winners_list = [winner[1] for winner in sorted_winners]
return winners_list


if __name__ == '__main__':
commits_file = 'commits.txt'
result_file = 'result.txt'
number_of_winners = 3

commits_dict = read_commits(commits_file)
winners = find_winners(commits_dict, number_of_winners)
write_winners(winners, result_file)
3 changes: 3 additions & 0 deletions result.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
AIvanov
CodeKiller777
AKalinina
71 changes: 71 additions & 0 deletions validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import re
from datetime import datetime


def validate_contributor(contributor: str, pattern=None) -> bool:
"""
A function to validate a contributor.
:return: True if the contributor is valid, False otherwise.
"""
# If a pattern is provided, use it to validate the contributor.
if pattern:
if pattern.fullmatch(contributor):
return True
return False
# Otherwise, use the default pattern.
if re.fullmatch(r'[A-Za-z_][A-Za-z_0-9]*', contributor):
return True
return False


def validate_commit_hash(commit_hash: str, pattern=None) -> bool:
"""
A function to validate a commit hash.
:return: True if the commit hash is valid, False otherwise.
"""
# If a pattern is provided, use it to validate the commit hash.
if pattern:
if pattern.fullmatch(commit_hash):
return True
return False
# Otherwise, use the default pattern.
if re.fullmatch(r'[a-z0-9]{7}', commit_hash):
return True
return False


def validate_date(date: str) -> bool:
"""
A function to validate a date.
:return: True if the date is valid, False otherwise.
"""
try:
datetime.strptime(date, '%Y-%m-%dT%H:%M:%S')
return True
except ValueError:
return False


def validate_commit(commit: str) -> bool:
"""
A function to validate a commit.
:return: True if the commit is valid, False otherwise.
"""
if not commit:
return False

commit_parts = commit.split()
if len(commit_parts) != 3:
return False

contributor, commit_hash, date = commit_parts
contributor_pattern = re.compile(r'[A-Za-z_][A-Za-z_0-9]*')
commit_hash_pattern = re.compile(r'[a-z0-9]{7}')

if not validate_commit_hash(commit_hash, commit_hash_pattern):
return False
if not validate_date(date):
return False
if not validate_contributor(contributor, contributor_pattern):
return False
return True