Skip to content
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
19 changes: 19 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Ruff
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Python
uses: actions/setup-python@v5
with:
python-version: "3.13.7"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install ruff pytest
- name: Run Ruff
run: ruff check --output-format=github .
- name: Run unit-tests
run: python -m pytest tests/*
79 changes: 79 additions & 0 deletions src/test_2/hamming_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
def hamming_encode(data):
m = len(data)
r = 0 # это контрольные биты
while (2**r) < (m + r + 1):
r += 1
total_length = m + r

encoded = [0] * total_length

j = 0
for i in range(1, total_length + 1):
# если позиции - степени двойки
if (i & (i - 1)) == 0:
continue
else:
encoded[i - 1] = data[j]
j += 1

for i_power in range(r):
index = 2**i_power
count_ones = 0
for i in range(1, total_length + 1):
if i & index:
if encoded[i - 1] == 1:
count_ones += 1
if count_ones % 2 != 0:
parity = 1
else:
parity = 0
# значение контрольного бита
encoded[index - 1] = parity
return encoded


def hamming_decode(encoded):
total_length = len(encoded)
r = 0
while (2**r) <= total_length:
r += 1

error_position = 0

for i_power in range(r):
index = 2**i_power
count_ones = 0
for i in range(1, total_length + 1):
if i & index:
if encoded[i - 1] == 1:
count_ones += 1
if count_ones % 2 != 0:
error_position += index

data = []
for i in range(1, total_length + 1):
if (i & (i - 1)) != 0:
data.append(encoded[i - 1])

return data, error_position


input_str = input("Введите строку битов для шифрования: ").strip()

if not all(c in "01" for c in input_str):
print("Ошибка! строка должна состоять только из 0 и 1")
exit()

data_bits = [int(c) for c in input_str]

# Кодируем
encoded_message = hamming_encode(data_bits)
print("Закодированное сообщение:", "".join(map(str, encoded_message)))

# Декодируем
corrected_data, error_pos = hamming_decode(encoded_message)

if error_pos == 0:
print("Ошибок не обнаружено")
else:
print(f"Обнаружена ошибка в позиции: {error_pos}")
Comment on lines +61 to +79
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если бы здесь можно было материться, я бы это делал. Не надо в модуль пихать неприкрытую if __name__ == "__main__" IO логику

27 changes: 27 additions & 0 deletions src/test_2/walkers_scheme.py
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не схема Уолкера, а наивный алгоритм. Тот факт, то у вас есть цикл в get_random должен на это намекать

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import random


class WalkerScheme:
def __init__(self, events):
# Проверяем, что список не пустой
if not events:
raise ValueError("Пустой список событий")
total_prob = 0
self.cumulative = []

# пороги, где заканчивается вероятность каждого события
for event, prob in events:
if prob < 0:
raise ValueError("Вероятность не может быть отрицательной")
total_prob += prob
self.cumulative.append((total_prob, event))
# Проверка суммы вероятностей
if abs(total_prob - 1) > 1e-6:
raise ValueError("Сумма вероятностей должна быть равна 1")

def get_random(self):
r = random.random()
for boundary, event in self.cumulative:
if r <= boundary:
return event
return self.cumulative[-1][1]
25 changes: 25 additions & 0 deletions tests/test_walkers_scheme.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import pytest
from src.test_2.walkers_scheme import WalkerScheme


def test_empty():
with pytest.raises(ValueError):
WalkerScheme([])


def test_negative_prob():
with pytest.raises(ValueError):
WalkerScheme([("a", 0.5), ("b", -0.1)])


def test_not_one_sum():
with pytest.raises(ValueError):
WalkerScheme([("a", 0.3), ("b", 0.3)]) # суммарно 0.6


def test_returns_valid_event():
scheme = WalkerScheme([("a", 0.5), ("b", 0.5)])
# Проверка случайного выбора
for _ in range(10):
event = scheme.get_random()
assert event in ("a", "b")