<jupyter_start><jupyter_text>Chapter 1  Problem BA1A: Compute the Number of Times a Pattern Appears in a Texthttp://rosalind.info/problems/ba1a/<jupyter_code>def PatternCount(Text, Pattern):
    count = 0
    overlap = len(Text) - len(Pattern) + 1
    for i in range(overlap):
        start = i
        end = i + len(Pattern)
        if Text[start:end] == Pattern:
            count += 1
    return count
PatternCount("GCGCG","GCG")<jupyter_output><empty_output><jupyter_text>Problem BA1B: Find the Most Frequent Words in a Stringhttp://rosalind.info/problems/ba1b/<jupyter_code># from ba1a.py import PatternCount
# uncomment when splitting into scripts

def FrequentWords(Text, k):
    frequent_patterns = set()
    count = {}
    
    # iterate through DNA Text and count kmers
    for i in range(len(Text) - k):
        pattern = Text[i : i + k]
        # add pattern to dictionary
        # key is i, start position of kmer
        # value is count, using PatternCount function from 1A
        count[i] = PatternCount(Text, pattern)
        
        # find maximum count value in dictionary
        max_count = max(count.values())
        
    # iterate through Text again, if count at that position is max count, slice that kmer and add to set
    for position in range(len(Text) - k):
        if count[position] == max_count:
            frequent_patterns.add(Text[position : position + k])
            
    return frequent_patterns
FrequentWords("ACGTTGCATGTCGCATGATGCATGAGAGCT", 4)<jupyter_output><empty_output><jupyter_text>Problem BA1C: Find the Reverse Complement of a Stringhttp://rosalind.info/problems/ba1c/<jupyter_code>def ReverseComplement(Text):
    complement = []
    for i in Text:
        if i == "A":
            complement.append("T")
        elif i == "T":
            complement.append("A")
        elif i == "G":
            complement.append("C")
        elif i == "C":
            complement.append("G")
        else:
            print("Not ACTG!")
    
    reverse_complement = list(reversed(complement))
    
    return "".join(reverse_complement)
ReverseComplement("AAAACCCGGT")<jupyter_output><empty_output><jupyter_text>Problem BA1D: Find All Occurances of a Pattern in a Stringhttp://rosalind.info/problems/ba1d/<jupyter_code>def LocatePatternMatch(Pattern, Genome):
    match_spot = []
    for i in range(len(Genome) - len(Pattern) + 1):
        if Genome[i : i + len(Pattern)] == Pattern:
            match_spot.append(i)
    return match_spot
LocatePatternMatch("ATAT", "GATATATGCATATACTT")<jupyter_output><empty_output><jupyter_text>Problem BA1E: Find Clumps in a Stringhttp://rosalind.info/problems/ba1e/<jupyter_code>def FindClumps(Genome, kmer_length, clump_length, times):
    # define length to search within
    clump_overlap = len(Genome) - clump_length + 1
    # kmer_overlap is looking within clump
    kmer_overlap = clump_length - kmer_length + 1
    # define kmers greater than times
    keepers = set()
    for clump_index in range(clump_overlap):
        # define clump window
        clump_start = clump_index
        clump_end = clump_index + clump_length
        clump = Genome[clump_start:clump_end]
        # define dictionary of kmers
        kmer_counts = {}
        for kmer_index in range(kmer_overlap):
            kmer_start = kmer_index
            kmer_end = kmer_index + kmer_length
            kmer = clump[kmer_start:kmer_end]
            if kmer in kmer_counts:
                # if kmer in dictionary, add count, +=
                kmer_counts[kmer] += 1
            else:
                # if kmer not in dictionary, add it
                kmer_counts[kmer] = 1
        # check if kmers occur greater than times
        for kmer in kmer_counts:
            if kmer_counts[kmer] >= times:
                keepers.add(kmer)
    return keepers
FindClumps("CGGACTCGACAGATGTGAAGAAATGTGAAGACTGAGTGAAGAGAAGAGGAAACACGACACGACATTGCGACATAATGTACGAATGTAATGTGCCTATGGC", 
5, 75, 4)<jupyter_output><empty_output><jupyter_text>Problem BA1F: Find Position in Genome to Minimize Skewhttp://rosalind.info/problems/ba1f/<jupyter_code>def MinimizeSkew(genome):
    skew_value = 0
    min_skew_value = 0
    skew_position = []
    # enumerate (genome, 1) means enumeration starts at 1 instead of 0
    for i, base in enumerate(genome, 1):
        if base.upper() == 'G':
            skew_value = skew_value + 1
        elif base.upper() == 'C':
            skew_value = skew_value - 1
        # C will cause decrease in value, check for new min
            if skew_value == min_skew_value:
                skew_position.append(i)
            elif skew_value < min_skew_value:
                min_skew_value = skew_value
                # recreate skew_position list if new min vale
                skew_position = [i]
    return skew_position
MinimizeSkew("CCTATCGGTGGATTAGCATGTCCCTGTACGTTTCGCCGCGAACTAGTTCACACGGCTTGATGGCAAATGGTTTTTCCGGCGACCGTAATCGTCCACCGAG")<jupyter_output><empty_output><jupyter_text>Problem BA1G: Compute Hamming Distance Between Two Stringshttp://rosalind.info/problems/ba1g/<jupyter_code>def HammingDistance(string1, string2):
    
    "This function calculates the Hamming Distance between two strings of equal length."
    
    # check if strings are the same length
    # alternate: assert len(string1) == len(string2), "Strings must be same length!"
    if len(string1) != len(string2):
        print("Strings must be the same length!")
        
    number_mismatches = 0
    string_length = len(string1)
    for i in range(string_length):
        if string1[i] != string2[i]:
            number_mismatches += 1
    return number_mismatches
HammingDistance("GGGCCGTTGGT", "GGACCGTTGAC")<jupyter_output><empty_output><jupyter_text>Problem BA1H: Find All Approximate Occurances of a Pattern in a Stringhttp://rosalind.info/problems/ba1h/<jupyter_code># from ba1g.py import HammingDistance

def ApproxPatternMatch(Pattern, Text, d):
    matches = []
    for i in range(len(Text) - len(Pattern) + 1):
        if HammingDistance(Text[i : i + len(Pattern)], Pattern) <= d:
            matches.append(i)
    return matches
ApproxPatternMatch("ATTCTGGA", "CGCCCGAATCCAGAACGCATTCCCATATTTCGGGACCACTGGCCTCCACGGTACGGACGTCAATCAAATGCCTAGCGGCTTGTGGTTTCTCCTACGCTCC", 3)<jupyter_output><empty_output><jupyter_text>Problem BA1I: Find the Most Frequent Mismatches in a Stringhttp://rosalind.info/problems/ba1i/<jupyter_code># from ba1g.py import HammingDistance

def HammingDistance(string1, string2):
    
    "This function calculates the Hamming Distance between two strings of equal length."
    
    # check if strings are the same length
    # alternate: assert len(string1) == len(string2), "Strings must be same length!"
    if len(string1) != len(string2):
        print("Strings must be the same length!")
        
    number_mismatches = 0
    string_length = len(string1)
    for i in range(string_length):
        if string1[i] != string2[i]:
            number_mismatches += 1
    return number_mismatches

def GenerateMismatchedKmers(kmer, h_dist):
    mismatched_list = []
    if h_dist == 0:
        return [kmer]
    elif len(kmer) == 1:
        return ["A", "C", "G", "T"]
    
    # generate neighbor mismatches
    for neighbor in GenerateMismatchedKmers(kmer[1:], h_dist):
        if HammingDistance(kmer[1:], neighbor) < h_dist:
            mismatched_list += ["A" + neighbor, "C" + neighbor, "G" + neighbor, "T" + neighbor]
        else:
            mismatched_list += [kmer[0] + neighbor]
    return mismatched_list

def FindFrequentMismatchWords(Text, k, d):
    kmerDictionary = {}
    for start in range(len(Text) - k + 1):
        kmer = Text[start : start + k]
        # Call GenerateMismatchedKmers with kmer , Hamming Distance value
        mismatched_kmers = GenerateMismatchedKmers(kmer, d)
        for km in mismatched_kmers: 
            if km in kmerDictionary:
                kmerDictionary[km] += 1
            else:
                kmerDictionary[km] = 1
    maxCount = max(kmerDictionary.values())
    frequent_kmers = []
    # iterate through dictionary for kmer(s) with count equal to maxCount
    for kmer, count in kmerDictionary.items():
        if count == maxCount:
            frequent_kmers.append(kmer)
    return frequent_kmers
FindFrequentMismatchWords("ACGTTGCATGTCGCATGATGCATGAGAGCT", 4, 1)<jupyter_output><empty_output><jupyter_text>Problem BA1J: Finding the Most Frequent Mismatches in String and its Complementhttp://rosalind.info/problems/ba1j/<jupyter_code># from ba1c.py import ReverseComplement
# from ba1g.py import HammingDistance

def ReverseComplement(Text):
    complement = []
    for i in Text:
        if i == "A":
            complement.append("T")
        elif i == "T":
            complement.append("A")
        elif i == "G":
            complement.append("C")
        elif i == "C":
            complement.append("G")
        else:
            print("Not ACTG!")
            
    reverse_complement = list(reversed(complement))
    return "".join(reverse_complement)

def HammingDistance(string1, string2):
    
    "This function calculates the Hamming Distance between two strings of equal length."
    
    # check if strings are the same length
    # alternate: assert len(string1) == len(string2), "Strings must be same length!"
    if len(string1) != len(string2):
        print("Strings must be the same length!")
        
    number_mismatches = 0
    string_length = len(string1)
    for i in range(string_length):
        if string1[i] != string2[i]:
            number_mismatches += 1
    return number_mismatches

def GenerateMismatchedKmers(kmer, h_dist):
    mismatched_list = []
    if h_dist == 0:
        return [kmer]
    elif len(kmer) == 1:
        return ["A", "C", "G", "T"]
    
    # generate neighbor mismatches
    for neighbor in GenerateMismatchedKmers(kmer[1:], h_dist):
        if HammingDistance(kmer[1:], neighbor) < h_dist:
            mismatched_list += ["A" + neighbor, "C" + neighbor, "G" + neighbor, "T" + neighbor]
        else:
            mismatched_list += [kmer[0] + neighbor]
    return mismatched_list

def FindFrequentMismatchWordsComplement(Text, k, d):
    kmerDictionary = {}
    for start in range(len(Text) - k + 1):
        kmer = Text[start : start + k]
        # make rev kmer
        reversed_kmer = ReverseComplement(kmer)
        # Call GenerateMismatchedKmers with kmer , Hamming Distance value
        mismatched_kmers = GenerateMismatchedKmers(kmer, d)
        # extend mismatched kmers to include rev possible kmers
        mismatched_kmers.extend(GenerateMismatchedKmers(reversed_kmer, d))
        for km in mismatched_kmers: 
            if km in kmerDictionary:
                kmerDictionary[km] += 1
            else:
                kmerDictionary[km] = 1
    maxCount = max(kmerDictionary.values())
    frequent_kmers = []
    # iterate through dictionary for kmer(s) with count equal to maxCount
    for kmer, count in kmerDictionary.items():
        if count == maxCount:
            frequent_kmers.append(kmer)
    return frequent_kmers
FindFrequentMismatchWordsComplement("ACGTTGCATGTCGCATGATGCATGAGAGCT", 4, 1)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.094302377747869, 'fraction_numerical': 0.00924181247196052, 'mean_word_length': 2.919127988748242, 'pattern_counts': {'":': 8, '<': 45, '<?xml version=': 0, '>': 42, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '193014', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3724, 'n_tokens_neox': 3538, 'n_words': 899, 'path': 'jessica/.ipynb_checkpoints/Bioinformatics Algorithms Chapter 1-checkpoint.ipynb', 'repo_name': 'dib-lab/bioinf_algorithms', 'size': '11145'}