Добавил:
ТГ: @Misskrinzhelika4 Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

км4

.pdf
Скачиваний:
1
Добавлен:
25.05.2026
Размер:
558.51 Кб
Скачать

Код программы:

def load_tuples_from_file(filename): data = []

try:

with open(filename, 'r') as file:

for line_num, line in enumerate(file, 1): line = line.strip()

if not line: continue

parts = line.split() if len(parts) != 2:

raise ValueError(f"Строка {line_num}: ожидается два числа, получено {len(parts)}")

pos = int(parts[0]) val = float(parts[1]) data.append((pos, val))

return data, None except Exception as e:

return None, f"Ошибка чтения {filename}: {e}"

def validate_positions(tuples_list): errors = []

positions = set()

for idx, (pos, val) in enumerate(tuples_list): if not isinstance(pos, int) or pos < 0:

errors.append(f"Индекс {idx}: недопустимая позиция {pos} (должна быть целым неотрицательным числом)")

else:

if pos in positions:

errors.append(f"Индекс {idx}: дубликат позиции {pos}") else:

positions.add(pos) return errors, positions

def restore_array(tuples_list): if not tuples_list:

return []

max_pos = max(pos for pos, _ in tuples_list) arr = [None] * (max_pos + 1)

for pos, val in tuples_list: if 0 <= pos <= max_pos:

arr[pos] = val return arr

def find_gaps_and_duplicates(tuples_list): pos_count = {}

for pos, _ in tuples_list:

pos_count[pos] = pos_count.get(pos, 0) + 1 if not pos_count:

return [], []

max_pos = max(pos_count.keys()) all_positions = set(range(max_pos + 1)) existing = set(pos_count.keys())

gaps = sorted(all_positions - existing)

duplicates = [(pos, count) for pos, count in pos_count.items() if count > 1] return gaps, duplicates

def save_output(arr, gaps, duplicates, filename): try:

with open(filename, 'w', encoding='utf-8') as f:

11

f.write("=== ВОССТАНОВЛЕННЫЙ МАССИВ ===\n")

for i, val in enumerate(arr):

f.write(f"позиция {i}: {val if val is not None else 'None'}\n") f.write("\n=== ПРОПУСКИ ПОЗИЦИЙ ===\n")

if gaps:

f.write("Пропущенные позиции: " + ", ".join(map(str, gaps)) + "\n") else:

f.write("Пропусков нет\n") f.write("\n=== ДУБЛИКАТЫ ПОЗИЦИЙ ===\n")

if duplicates:

for pos, cnt in duplicates:

f.write(f"Позиция {pos} встречается {cnt} раз(а)\n")

else:

f.write("Дублей нет\n") except Exception as e:

return f"Ошибка записи {filename}: {e}" return None

def save_errors(errors, filename): try:

with open(filename, 'w', encoding='utf-8') as f: if not errors:

f.write("Ошибок не обнаружено.\n") else:

for err in errors: f.write(err + "\n")

except Exception as e:

print(f"Ошибка записи ошибок: {e}")

def main():

input_file1 = 'input1.txt' input_file2 = 'input2.txt' output_file = 'output.txt' errors_file = 'errors.txt' all_errors = []

tuples1, err1 = load_tuples_from_file(input_file1) tuples2, err2 = load_tuples_from_file(input_file2)

if err1: all_errors.append(err1)

if err2: all_errors.append(err2)

if err1 or err2:

save_errors(all_errors, errors_file)

print("Ошибка загрузки файлов. Смотрите errors.txt") return

combined = tuples1 + tuples2

errors_pos, _ = validate_positions(combined) all_errors.extend(errors_pos)

arr = restore_array(combined)

gaps, duplicates = find_gaps_and_duplicates(combined)

save_output(arr, gaps, duplicates, output_file) if all_errors:

save_errors(all_errors, errors_file) else:

save_errors([], errors_file) # создаст файл с "Ошибок не обнаружено"

12

print(f"Готово. Результаты в {output_file}, ошибки в {errors_file}")

if __name__ == "__main__": main()

Входные/выходные данные

Входные

Выходные данные

Ожидаемый

Смысл теста

теста

данные

 

результат

 

1

Input1.txt

===

совпадает

Нормальный,

 

0

25.7

ВОССТАНОВЛЕННЫЙ

 

найдены

 

4

69.4

МАССИВ ===

 

дубликаты и

 

2

89.1

позиция 0: 25.7

 

пропуски

 

Input2.txt

позиция 1: 89.2

 

 

 

6

58.7

позиция 2: 48.6

 

 

 

2

48.6

позиция 3: None

 

 

 

1

89.2

позиция 4: 69.4

 

 

 

 

 

позиция 5: None

 

 

 

 

 

позиция 6: 58.7

 

 

 

 

 

=== ПРОПУСКИ

 

 

 

 

 

ПОЗИЦИЙ ===

 

 

 

 

 

Пропущенные позиции:

 

 

 

 

 

3, 5

 

 

 

 

 

=== ДУБЛИКАТЫ

 

 

 

 

 

ПОЗИЦИЙ ===

 

 

 

 

 

Позиция 2 встречается 2

 

 

 

 

 

раз(а)

 

 

2

Input1.txt

output: массив с

Ошибка

Исключительный:

 

2

3.5

позицией 0 = 20,

формата

неверный данные

 

Input2.txt

пропуски 0,1; в errors.txt

 

во втором файле

 

d c

ошибка чтения input2.txt

 

 

 

 

 

 

 

 

Табл. № 9

13

Рис. № 3. Проверка массива кортежей

14