编写一个程序,计算 PYTHON3 中 0 和 1 的输入序列中“11”出现的次数
Write a program that counts the number of occurrences of "11" in an input sequence of zeros and ones in PYTHON3
假设我输入一个像 [0,0,1,1,1,0] 这样的列表,程序应该打印 2。我写了一个像这样的简单程序:
def count11(seq):
n= len(seq)
print (n)
cnt=0
#i=0;
print(cnt)
#print(i)
for i in range (0,n):
if(seq[i] and seq[i+1]==1):
cnt+=1;
#i+=1;
return cnt
print(count11([0, 0, 1, 1, 1, 0]))
但是这个条件在极端情况下是行不通的。就像 len(seq)=5 和 i=4 时循环将显示错误。
你能帮我解决这个问题吗?提前致谢。
只是解决一些问题
def count11(seq):
n = len(seq)
print(n)
cnt = 0
# i=0;
print(cnt)
# print(i)
for i in range(0, n - 1):
if seq[i] == 1 and seq[i + 1] == 1:
cnt += 1
# i+=1;
return cnt
print(count11([0, 0, 1, 1, 1, 0]))
假设我输入一个像 [0,0,1,1,1,0] 这样的列表,程序应该打印 2。我写了一个像这样的简单程序:
def count11(seq):
n= len(seq)
print (n)
cnt=0
#i=0;
print(cnt)
#print(i)
for i in range (0,n):
if(seq[i] and seq[i+1]==1):
cnt+=1;
#i+=1;
return cnt
print(count11([0, 0, 1, 1, 1, 0]))
但是这个条件在极端情况下是行不通的。就像 len(seq)=5 和 i=4 时循环将显示错误。 你能帮我解决这个问题吗?提前致谢。
只是解决一些问题
def count11(seq):
n = len(seq)
print(n)
cnt = 0
# i=0;
print(cnt)
# print(i)
for i in range(0, n - 1):
if seq[i] == 1 and seq[i + 1] == 1:
cnt += 1
# i+=1;
return cnt
print(count11([0, 0, 1, 1, 1, 0]))