Untitled
unknown
python
3 years ago
2.7 kB
11
Indexable
class DNA:
"""
Represents a DNA strand of an arbitrary length
"""
def __init__(self, n):
"""
input: int
return: none
initializes the object with a length and a randomly generated strand of DNA
"""
self.length = n
self.strand = ""
for i in range(n):
self.strand += random.choice(['A', 'T', 'C', 'G'])
def __str__(self):
"""
input: none
return: str
returns a string representation of a DNA object
"""
return self.strand + " of length " + str(self.length)
def is_complement(self, other):
"""
input: object (DNA)
return: bool
takes a DNA object and returns True if the calling object is a complement.
Otherwise, it returns False
"""
complement_dict = {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C'
}
if self.length != other.length:
return False
# Compare each pair of bases in the two strands. If any pair of bases
# is not a complement, return False
for self_base, other_base in zip(self.strand, other.strand):
if complement_dict[self_base] != other_base:
return False
return True
def is_reverse(self, other):
"""
input: objects (DNA)
return: bool
takes two DNA object and returns True if the first object is the reverse of the
second object, and False otherwise.
"""
return self.strand == other.strand[::-1]
def main():
"""
creates several DNA objects and
tests if they are complements and reverse of each other
"""
dna_strands = []
while True:
try:
n = int(input("Length of DNA strand? "))
r = int(input("Number of strands to test? "))
# if one of the inputs are negative numbers raise value error
if n <= 0 or r <= 0:
raise ValueError("\nNumbers must be positive. Please Try again")
break
except ValueError as e:
print(f"\n{e}")
except Exeption as e:
print("\nInvalid Input, please try again.")
# Create r DNA objects and append them to the list
for _ in range(r):
dna = DNA(n)
print(f'Creating strand: {dna}')
dna_strands.append(dna)
print("\nComplement test:")
# test compliment
for dna_obj in dna_strands:
for other_dna in dna_strands:
if dna_obj.is_complement(other_dna):
print(f"{dna_obj.strand} is the complement of {other_dna.strand}")
print("Done")
print("\nReverse test:")
# test reverse
for dna in dna_strands:
for other in dna_strands:
result = is_reverse(dna, other)
if result:
print(f"{dna.strand} is the reverse of {other.strand}")
print("Done")
if __name__ == "__main__":
main()Editor is loading...