我正在尝试学习算法/数据结构。为了提高我的知识,我试图解决一些在线问题。 我试图解决的问题之一是practiceque
我试过以下方法:
def count_zero_one_two():
s = '102100211'
s_len = len(s)
count = 0
for i in range (s_len-1):
j = i+1
k = j+1
#print i, j, k, count
#print s[i], s[j], s[k]
if k > (s_len-1):
print "end"
break
elif (s[i] != s[j]) and (s[i] !=s[k]) and (s[j] != s[k]):
print s[i], s[j], s[k]
print "not equal"
count = count+1
#print count
else:
print s[i], s[j], s[k]
print "equal"
k = j +i
print count
count_zero_one_two()
问题:如果我的输入字符串是“102100211”,那么计数应为5,但我得到4.任何想法?
答案 0 :(得分:2)
我会这样解决:
def count_zero_one_two(s):
num = 0
for i in range(len(s)):
for j in range(1, len(s)/3 + 1):
if all(s[i:i+3*j].count(n) == j for n in '012'):
num += 1
return num
all()
用于检查所有3个字符(每次迭代)是否都在'012'。
内部for
循环用于计算长度为3,6,9等的序列中的0,1和2的数量。
<强>输出:强>
>>> s = '0102010'
>>> count_zero_one_two(s)
2
>>>
>>> s = '102100211'
>>> count_zero_one_two(s)
5
答案 1 :(得分:0)
from collections import Counter
def countSub(s):
result = []
for i in range(3, len(s), 3):
t = s[:i]
c = list(Counter(t).values())
if (c[0]==c[1]==c[2]):
result.append((t, c[0]))
return result
def count(s):
result = []
for i in range(len(s)-2):
result.extend(countSub(s[i:]))
return set(result)
ss = count("102100211")
print("%s substrings found: " % len(ss), ss)
输出:
4 substrings found (not counting duplicates and empty strings):
{('021', 1), ('210021', 2), ('210', 1), ('102', 1)}