
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Program to find total sum of all substrings of a number given as string in Python
Suppose we have a number in string format, and we have to find the sum of all substrings of s. The answer may be very large, so return result modulo 10^9+7.
So, if the input is like s = "268", then the output will be 378 as the substrings are "2", "6", "8", "26", "68" and "268" total sum is 378.
To solve this, we will follow these steps −
- M := 10^9 + 7
- sum_val := 0
- B := 1
- res := 0
- for i in range size of s - 1 down to 0, decrease by 1, do
- res :=(res + digit value of s[i] * B *(i + 1)) mod M
- sum_val := sum_val - digit value of s[i]
- B := (B * 10 + 1) mod M
- return res
Example
Let us see the following implementation to get better understanding −
def solve(s): M = 10 ** 9 + 7 sum_val = 0 B = 1 res = 0 for i in range(len(s) - 1, -1, -1): res = (res + int(s[i]) * B * (i + 1)) % M sum_val -= int(s[i]) B = (B * 10 + 1) % M return res s = "268" print(solve(s))
Input
"268"
Output
378
- Related Articles
- Program to find out number of distinct substrings in a given string in python
- Program to find sum of beauty of all substrings in Python
- Program to find total similarities of a string and its substrings in Python
- Program to print all substrings of a given string in C++
- Program to find the sum of all digits of given number in Python
- Program to find out the substrings of given strings at given positions in a set of all possible substrings in python
- Program to find number of different substrings of a string for different queries in Python
- C# Program to find all substrings in a string
- C++ Program to find minimal sum of all MEX of substrings
- Program to find split a string into the max number of unique substrings in Python
- Program to find all substrings whose anagrams are present in a string in Python
- Count the number of vowels occurring in all the substrings of given string in C++
- Count Unique Characters of All Substrings of a Given String in C++
- Program to find maximum number of non-overlapping substrings in Python
- Program to find sum of the 2 power sum of all subarray sums of a given array in Python

Advertisements