-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBA1I.py
70 lines (61 loc) · 2.12 KB
/
BA1I.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from itertools import product
from BA1A import patternCount
datasetFile = open("datasets/rosalind_ba1i.txt", "r")
text = datasetFile.readline().strip()
k, d = map(lambda x: int(x), datasetFile.readline().strip().split(" "))
print("Find the Most Frequent Words with Mismatches in a String")
neighborsCache = {}
def getCache(pattern, d):
if pattern in neighborsCache:
forPattern = neighborsCache[pattern]
if not forPattern is None:
if str(d) in forPattern:
return forPattern[str(d)]
return None
def setCache(pattern, d, val):
forPattern = {}
if pattern in neighborsCache:
forPattern = neighborsCache[pattern]
forPattern[str(d)] = val
neighborsCache[pattern] = forPattern
def getNeighbors(pattern, d):
cached = getCache(pattern, d)
if cached is not None:
return cached
neighbors = set([pattern])
if (d == 0) or len(pattern) == 0:
return neighbors
alphabet = 'ATCG'
for base in alphabet:
if not (pattern[0] == base):
suffixes = getNeighbors(pattern[1:], d - 1)
else:
suffixes = getNeighbors(pattern[1:], d)
for suffix in suffixes:
neighbors.add(base + suffix)
setCache(pattern, d, neighbors)
return neighbors
def frequentWordsWithMismatches(text, k, d):
counts = {}
for i in range(len(text) - k + 1):
pattern = text[i:i+k]
neighborhood = getNeighbors(pattern, d)
for neighbor in neighborhood:
if neighbor in counts:
counts[neighbor] += 1
else:
counts[neighbor] = 0
frequentPatterns = set()
maxCount = None
for pattern in counts:
count = counts[pattern]
if maxCount is None or count > maxCount:
frequentPatterns = set([pattern])
maxCount = count
elif count == maxCount:
frequentPatterns.add(pattern)
return frequentPatterns, maxCount
frequentPatterns, maxCount = frequentWordsWithMismatches(text, k, d)
solution = " ".join(frequentPatterns)
outputFile = open("output/rosalind_ba1i.txt", "w")
outputFile.write(solution)