Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of ways we can make a list of values by splitting numeric string in Python
Suppose we have a string s containing digits from 0-9 and another number k. We need to find the number of different ways that s can be represented as a list of numbers from [1, k]. If the answer is very large, return result mod 10^9 + 7.
So, if the input is like s = "3456", k = 500, then the output will be 7, as we can represent s like [3, 4, 5, 6], [34, 5, 6], [3, 4, 56], [3, 45, 6], [34, 56], [345, 6], [3, 456].
Algorithm Approach
We'll use dynamic programming to solve this problem. The approach works as follows:
m := 10^9 + 7 (modulo value)
N := size of string s
dp := array of size (N + 1) filled with 0
dp[N] := 1 (base case - empty string has one way)
-
For each position i from N-1 to 0:
Try all possible numbers starting from position i
If the number is within range [1, k], add ways from remaining string
If number exceeds k, break (larger numbers will also exceed k)
Return dp[0] (ways to split entire string)
Example
class Solution:
def solve(self, s, k):
m = 10 ** 9 + 7
N = len(s)
dp = [0] * (N + 1)
dp[N] = 1
for i in range(N - 1, -1, -1):
curr_val = 0
for j in range(i, N):
curr_val = curr_val * 10 + int(s[j])
if 1 <= curr_val <= k:
dp[i] = (dp[i] + dp[j + 1]) % m
else:
break
return dp[0]
# Test the solution
ob = Solution()
s = "3456"
k = 500
print(ob.solve(s, k))
7
How It Works
The algorithm uses bottom-up dynamic programming:
Base Case: dp[N] = 1 represents that an empty suffix has exactly one way to be split (empty list)
State Definition: dp[i] represents the number of ways to split substring s[i:] into valid numbers
Transition: For each position i, we try forming numbers of different lengths starting from i. If a number is valid (? k), we add the ways to split the remaining string
Another Example
# Test with a smaller example
ob = Solution()
s = "12"
k = 15
result = ob.solve(s, k)
print(f"String: {s}, k: {k}")
print(f"Ways to split: {result}")
print("Valid splits: [1,2], [12]")
String: 12, k: 15 Ways to split: 2 Valid splits: [1,2], [12]
Conclusion
This dynamic programming solution efficiently counts all valid ways to split a numeric string into numbers within a given range. The time complexity is O(N²) where N is the string length, making it suitable for most practical inputs.
