我得到了一个字符串,我必须计算每个位对距离的和,其中两个位都是1.
For example the given string of 100101 would have the distance of 10
100101 (3)
100101 (5)
100101 (2)
因此,距离之和是3+5+2=10.
我目前的代码如下,我不能真正解决问题,我应该如何处理这个问题.
def pairs(s):
count = 0
for i in range(len(s)):
if s[i] == '1':
for j in range(i+1, len(s)):
if s[j] == '1':
count += 1
return count
if __name__ == "__main__":
print(pairs("100101")) #10
我也曾try 将1存储在列表中,但无法计算出距离.