patternpythonMinor
Where should I place the constant?
Viewed 0 times
theconstantwhereplaceshould
Problem
The following bit of code requires a
I have written three versions of the program that place the table at different locations in the code. The differing placement of the table results in quite varying performance in the creation of
So, which one of these variants is preferable? Or is there even a different, better solution?
Version 1:
Version 2:
Version 3:
string.maketrans table that is only used inside a single function.I have written three versions of the program that place the table at different locations in the code. The differing placement of the table results in quite varying performance in the creation of
DNA instances and calls to the to_rna method.So, which one of these variants is preferable? Or is there even a different, better solution?
Version 1:
from string import maketrans
DNA_RNA_TRANSLATION_TABLE = maketrans('GCTA', 'CGAU')
class DNA(object):
"""Represent a strand of DNA."""
def __init__(self, dna_string):
self.dna_string = dna_string
def to_rna(self):
"""Return the RNA complement of the DNA strand."""
return self.dna_string.translate(DNA_RNA_TRANSLATION_TABLE)Version 2:
from string import maketrans
class DNA(object):
"""Represent a strand of DNA."""
__rna_translation_table = maketrans('GCTA', 'CGAU')
def __init__(self, dna_string):
self.dna_string = dna_string
def to_rna(self):
"""Return the RNA complement of the DNA strand."""
return self.dna_string.translate(self.__rna_translation_table)Version 3:
from string import maketrans
class DNA(object):
"""Represent a strand of DNA."""
def __init__(self, dna_string):
self.dna_string = dna_string
def to_rna(self):
"""Return the RNA complement of the DNA strand."""
translation_table = maketrans('GCTA', 'CGAU')
return self.dna_string.translate(translation_table)Solution
I will answer your question in an unexpected way : the better solution is, as far as I can tell, much more straightforward than what you are doing.
Indeed, you don't need a class : your class has an
I think see this the neatest solution. Then if on only want to create the table only once for performance reason, you can put it a variable outside the function but it's probably not needed.
Indeed, you don't need a class : your class has an
__init__ and a single method to_rna, it might as well be a single function.from string import maketrans
def dna_to_rna(dna_string):
"""Return the RNA complement of the DNA strand."""
return dna_string.translate(maketrans('GCTA', 'CGAU'))I think see this the neatest solution. Then if on only want to create the table only once for performance reason, you can put it a variable outside the function but it's probably not needed.
Code Snippets
from string import maketrans
def dna_to_rna(dna_string):
"""Return the RNA complement of the DNA strand."""
return dna_string.translate(maketrans('GCTA', 'CGAU'))Context
StackExchange Code Review Q#44164, answer score: 6
Revisions (0)
No revisions yet.