Reputation: 11
There is a binary string. We have to count number of substrings starting and ending with '1'. I have gone with this approach but not getting desired output Please tell me where does code fails.
Code-:
st="1001101"
c=0
for i in st:
if i=='1':
for j in st[st.index(i)+1:]:
if j=='1':
c+=1
print(c)
Upvotes: 0
Views: 43
Reputation: 54168
The problem is with st.index(i)
because as you have multiple 1
it always take the first
You may use enumerate
to get both index and letter, for start letter
value = "1001101"
counter = 0
for idx, iletter in enumerate(value):
if iletter == '1':
for jletter in value[idx + 1:]:
if jletter == '1':
counter += 1
print(counter) # 6
Using a list comprehension, you can also compute the pairs of indexes that matches the requirement, then just take the length
pairs = [(i, j) for i in range(len(value))
for j in range(i + 1, len(value))
if value[i] == value[j] == "1"]
# [(0, 3), (0, 4), (0, 6), (3, 4), (3, 6), (4, 6)]
print(len(pairs)) #6
Upvotes: 2
Reputation: 704
This is in fact a math question...to know the answer, you only need to count number of 1's (call this c1), then the answer is nCr(n=c1, r=2)
st="1001101"
c1=0
for i in st:
if i=='1': c1+=1
c=c1*(c1-1)//2
print(c)
BTW, the code in question fails because st.index(i)
is always 1. You find the first occurrence of i='1' from st, but st starts with a '1' (or logically the first '1' from string). To correct it:
st="1001101"
c=0
st_len=len(st)
for i in range(0, st_len):
if st[i]=='1':
for j in range(i+1, st_len):
if st[j]=='1':
c+=1
print(c)
Upvotes: 1