문제
https://www.hackerrank.com/challenges/bear-and-steady-gene/problem?isFullScreen=true
문제 요약
아이디어
1차 고뇌
코드(유효성 실패)
from collections import Counter
def steadyGene(gene):
# Write your code here
gene_len = len(gene)
expected_len = gene_len//4
lst = ["G", "A", "C", "T"]
occur = Counter()
found = Counter()
target = set()
for char in lst:
cnt = gene.count(char) - expected_len
if cnt > 0 :
occur[char] = cnt
found[char] = 0
target.add(char)
least = sum(occur.values())
if least == 0:
return 0
"""
ver1
"""
for i in range(least, gene_len):
for j in range(0, gene_len-i+1):
if (i+j)-(j) < least:
break
elif gene[j] not in occur:
continue
if not (occur - Counter(gene[j:i+j])):
return (i+j)-(j)
"""
ver2
"""
start = 0
end = least - 1
while end != gene_len:
if end == gene_len and start+least >= end:
break
cur = Counter(gene[start:end])
check = occur - cur
check2 = gene[start] in occur
# print("! ", start, end, cur, check, check2)
if not check:
all_lst.append(len(gene[start:end]))
start += 1
else:
end += 1
if not check2:
start+=1
return min(all_lst)
코드(성공)
from collections import Counter
def steadyGene(gene):
# Write your code here
gene_len = len(gene)
expected_len = gene_len//4
lst = ["G", "A", "C", "T"]
occur = Counter()
found = Counter()
target = set()
for char in lst:
cnt = gene.count(char) - expected_len
if cnt > 0 :
occur[char] = cnt
found[char] = 0
target.add(char)
least = sum(occur.values())
if least == 0:
return 0
"""
ver3
"""
tail = 0
head = 0
print(found)
min_len = gene_len
while head != gene_len:
found[gene[head]] += 1
flag = True
print(found)
for t_char in target:
if found[t_char] < occur[t_char]: # need to find(include) more characters in 'found'
flag = False
if flag == True:
# this is a valid candidate
min_len = min(min_len, head-tail+1)
# try to shorten it by cutting the left
while found[gene[tail]] > occur[gene[tail]]:
found[gene[tail]] -= 1
tail += 1
min_len = min(min_len, head-tail+1)
head += 1
return min_len