Exercise 1: Complement a DNA string


In [1]:
def complement(dna):
    '''
    This function complements DNA. If characters other than 
    "ATGCatgc-" are in your DNA, this function raises an ValueError.
    An empty DNA complements to an empty DNA.
    Whitespaces is not allowed in the input.
    '''
    # Raise a ValueErrer if invalid characters are in the DNA
    valid_chars = list('atgcATGC')
    if not all([(char in valid_chars) for char in dna]):
        raise ValueError    
    
    # Keep the case of the DNA.
    dna = dna.translate(str.maketrans('ATGCatgc','TACGtacg'))
    return dna

In [2]:
# Test the function with several strings
test_dnas =['atgc  agaggattcc', 'ATGCATblubAatAggcA',
            'ATAATTTAGGCCAGATAC', 'GGGGGCCATATA',
            'ga--atg-tgaat--gtga', '', 'This is not DNA']

for dna in test_dnas:
    try:
        print('The Input: {:20} Output: {}'.format(dna, complement(dna)))
    except ValueError:
        print('The input "{}" has no valid complement.'.format(dna))


The input "atgc  agaggattcc" has no valid complement.
The input "ATGCATblubAatAggcA" has no valid complement.
The Input: ATAATTTAGGCCAGATAC   Output: TATTAAATCCGGTCTATG
The Input: GGGGGCCATATA         Output: CCCCCGGTATAT
The input "ga--atg-tgaat--gtga" has no valid complement.
The Input:                      Output: 
The input "This is not DNA" has no valid complement.

Exercise 2: Multiply two polynomials


In [3]:
def sign(number):
    '''
    Return the sign of a given number.
    '''
    if number >= 0:
        return '+'
    else: 
        return '-'
    
def print_polynom(poly):
    '''
    Print the list representation of a polynom as an
    easy readable string.
    '''
    output = ''
    for i in range(len(poly)):
        output += ' {} {}x^{} '.format(sign(poly[i]),
                                      abs(poly[i]), i)
        output = output.strip('+ ')
    return output

def clean_polynom(poly):
    '''
    This function removes
    '''
    for i in range(len(poly)-1,-1,-1):
        if poly[i] == 0:
            poly.pop(i)
        else:
            break
        if poly == []:
            poly = [0]
    return poly

def multiply_polynoms(polyA, polyB):
    '''
    This fuction takes two lists as parameters which represent polynoms.
    It returns the product of those two polynomes.
    '''
    result = [0]*(len(polyA)+len(polyB)-1)
    for i in range(len(polyA)):
        for j in range(len(polyB)):
            result[i+j] += polyA[i]*polyB[j]    
    return clean_polynom(result)

In [4]:
# Test the functions for several polynoms
polynoms = [[[1,1], [1,1], [1,2,1]],
            [[1,1,1], [1,1,1], [1,2,3,2,1]],
            [[1,1], [0], [0]],]

for poly1, poly2, result in polynoms:
    computed = multiply_polynoms(poly1, poly2)
    if computed != result:
        print('The function does not work proberly.')
    else:
        print('({}) * ({}) = {}'.format(print_polynom(poly1),
                                        print_polynom(poly2),
                                        print_polynom(computed)))


(1x^0 + 1x^1) * (1x^0 + 1x^1) = 1x^0 + 2x^1 + 1x^2
(1x^0 + 1x^1 + 1x^2) * (1x^0 + 1x^1 + 1x^2) = 1x^0 + 2x^1 + 3x^2 + 2x^3 + 1x^4
(1x^0 + 1x^1) * (0x^0) = 0x^0

Exercise 3: Anagram checker


In [5]:
def is_anagram(text1, text2):
    '''
    The function returns True if it's parameter string is a anagram. 
    If it is not a palindrom it returns False.
    '''
    import string
    # Remove all punctuation characters and whitespace
    text1 = text1.translate(str.maketrans("","",
                                        string.punctuation+
                                        string.whitespace+
                                        string.digits))
    text2 = text2.translate(str.maketrans("","",
                                        string.punctuation+
                                        string.whitespace+
                                        string.digits))
    text1 = text1.lower()
    text2 = text2.lower()
    
    x = {x:text1.count(x) for x in set(text1)}
    y = {x:text2.count(x) for x in set(text2)}
    if x == y:
        return True
    else:
        return False

In [6]:
# Test the function for several palindroms
test_text =[['Anna','Anna'],
            ['','Anna'],
            ['Anna', ''],
            ['UFO tofu?','Tofu UFO!'],
            ['Anna', 'Paul'],
            ['Dichtungsring', 'Richtungsding']]

for text1, text2 in test_text:
    #Remove all punctuation characters for a clean output.
    if is_anagram(text1, text2):
        print('"{}" is a anagram of "{}"'.format(text1, text2))
    else:
        print('"{}" is not a anagram of "{}"'.format(text1, text2))


"Anna" is a anagram of "Anna"
"" is not a anagram of "Anna"
"Anna" is not a anagram of ""
"UFO tofu?" is a anagram of "Tofu UFO!"
"Anna" is not a anagram of "Paul"
"Dichtungsring" is a anagram of "Richtungsding"