Hw14 part II#3
Conversation
Add create_results_dir_if_doesnt_exist function
eksytnik
left a comment
There was a problem hiding this comment.
Увы, не совсем реализовано то, что было в задании. Есть начало работы с классами, но сами классы полноценно не реализованы.
FastQ - 3 балла.
Биологические последовательности - 7 баллов.
| sequence_to_str_list = [] | ||
| for nucleotide in self: | ||
| sequence_to_str_list.append(nucleotide) | ||
| return ''.join(sequence_to_str_list) |
There was a problem hiding this comment.
Получается создание строки из строки через список. Интересно, но цель не ясна с:
| def __init__(self, sequence: str): | ||
| self.alphabet = 'AUGCaugc' | ||
| self.complement_dictionary = { | ||
| 'A': 'U', | ||
| 'U': 'A', | ||
| 'G': 'C', | ||
| 'C': 'G', | ||
| 'a': 'u', | ||
| 'u': 'a', | ||
| 'g': 'c', | ||
| 'c': 'g' | ||
| } |
There was a problem hiding this comment.
self - это ссылка на экземпляр класса. Такие штуки, как общие алфавиты - обычно нет смысла хранить на уровне экземпляра, это что-то общее и неизменное, их можно сделать классовыми атрибутами.
А вот sequence ровно наоборот - был смысл сделать именно атрибутом в self.
Должно было быть что-то в таком духе:
alphabet = '...'
complement_dict = {...}
def __init__(self, sequence: str):
self.sequence = sequence
| } | ||
|
|
||
| def transcribe(self) -> RNASequence: | ||
| transcription_dictionary = { |
| def run_dna_rna_tools(inputs: tuple) -> list | str: | ||
| """ | ||
| Produce a list of either transcripts, reverse sequences, complementary sequences or reverse complementary sequences | ||
| arguments: | ||
| - inputs (tuple): an arbitrary amount of strings where the last one is the name of desired operation, and other strings are sequences | ||
| return | ||
| - complement_seqs (list): a list of complementary sequences | ||
| """ | ||
| if len(inputs) < 2: | ||
| raise ValueError('Invalid input: the function requires at least one sequence and an operation name!') | ||
| *seqs, operation = inputs | ||
| if operation == 'transcribe': | ||
| transcribed_seqs = [] | ||
| for seq in seqs: | ||
| transcribed_seqs.append(str(DNASequence(seq).transcribe())) | ||
| return transcribed_seqs | ||
| elif operation == 'reverse': | ||
| result = reverse(seqs) | ||
| elif operation == 'complement': | ||
| complement_seqs = [] | ||
| for seq in seqs: | ||
| if 'U' in seq or 'u' in seq: | ||
| complement_seqs.append(str(RNASequence(seq).complement())) | ||
| else: | ||
| complement_seqs.append(str(DNASequence(seq).complement())) | ||
| return complement_seqs | ||
| elif operation == 'reverse_complement': | ||
| result = reverse_complement(seqs) | ||
| else: | ||
| raise ValueError('Invalid input: unknown operation! Check the last argument.') | ||
| if len(result) == 1: | ||
| result = ''.join(result) | ||
| return result |
There was a problem hiding this comment.
Получилось немного смешанное задание. Подразумевалось, что вся реализация через функции будет переписана на классы, и это всё станет методами или атрибутами классов, а вышло нечто смешанное и в результате не совсем то, что требовалось.
| quality_check = sum(quality_per_letter) / len(quality_per_letter) >= quality_threshold | ||
| if gc_check and length_check and quality_check: | ||
| seqs_filtered.append(record) | ||
| return seqs_filtered |
There was a problem hiding this comment.
Не хватает чтения и записи через методы библиотек.
| return info_dict | ||
|
|
||
|
|
||
| def reverse(seqs: list) -> list: |
There was a problem hiding this comment.
Функции должны были стать методами классов.
| dna_transcript_list = [] | ||
| for nucleotide in self: | ||
| dna_transcript_list.append(transcription_dictionary[nucleotide]) | ||
| return RNASequence(''.join(dna_transcript_list)) |
There was a problem hiding this comment.
Можно делать как-то так. Получается одновременно короче и более читаемо:
transcribed_sequence = ''.join(transcription_dictionary[nucleotide] for nucleotide in self.sequence)
return RNASequence(transcribed_sequence)
| """ | ||
| reverse_seqs = [] | ||
| for seq in seqs: | ||
| reverse_seqs.append(seq[::-1]) |
There was a problem hiding this comment.
seq[::-1] работает на строках без доп списков.
| if not self.is_correct_alphabet(): | ||
| raise InvalidInputError('Cannot complement: incorrect input sequence. Only nucleotides (in both cases) are supported!') |
There was a problem hiding this comment.
Проверка то хорошая, только на уровне complement как будто чуть поздно, это стоит делать на попытке создать такой экземпляр класса.
| for nucleotide in self: | ||
| if nucleotide == 'G' or nucleotide == 'C' or nucleotide == 'g' or nucleotide == 'c': | ||
| gc_count += 1 | ||
| return gc_count / len(self) |
There was a problem hiding this comment.
Всегда классно предусматривать, что пользователь может дать пустую последовательность. Например, потому что у него что-то криво прочиталось в скрипте, работающем с файлами с данными. Ошибку деления на ноль он и так увидит, конечно, но.
No description provided.