Skip to content

Commit f68a264

Browse files
authored
Merge pull request #1162 from Abhinavcode13/patch-10
Create Substrings_with_1.py
2 parents cb2d08e + b9937dc commit f68a264

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Math/Substrings_with_1.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'''Name : Abhinav kumar
2+
Github username : Abhinavcode13
3+
Repository name : data-structures-and-algorithms
4+
Problem : Number of Substrings With Only 1s in Python
5+
Issue Number : #518
6+
Problem statement :
7+
8+
Explanation of the below Python code :
9+
10+
The implementation is quite similar to the C++ implementation. We iterate over the string s using a for loop and keep track of the count of consecutive 1's using the variable count. Whenever we encounter a '0', we calculate the number of substrings that can be formed using the formula n*(n+1)/2, add it to the final answer ans, and reset the value of count to 0. Finally, we calculate the number of substrings for the last substring of consecutive 1's, add it to the final answer ans, and return the result modulo 10^9 + 7. Note that we have used the integer division operator // to perform the division in Python.
11+
12+
13+
14+
'''
15+
16+
----------------------------------------------------------------------------------------------//Python code begins here--------------------------------------------------------------------------------------------------------------------------------------
17+
class Solution:
18+
def numSub(self, s: str) -> int:
19+
count = 0 # count the number of consecutive ones
20+
ans = 0 # variable to store the final answer
21+
for i in range(len(s)):
22+
if s[i] == '1':
23+
count += 1
24+
else:
25+
# calculate the number of possible substrings that can be formed
26+
# from the current consecutive ones and add it to the final answer
27+
ans = (ans + (count*(count+1))//2) % (10**9 + 7)
28+
count = 0
29+
# handle the case when the string ends with consecutive ones
30+
ans = (ans + (count*(count+1))//2) % (10**9 + 7)
31+
return ans

0 commit comments

Comments
 (0)