 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to count number of ways we can make a list of values by splitting numeric string in Python
Suppose we have a strings s. The s is containing digits from 0 - 9 and we also have another number k. We have 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 then 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]
To solve this, we will follow these steps −
- m := 10^9 + 7 
- N := size of s 
- dp := a list of size (N + 1) and fill with 0 
- dp[N] := 1 
-  for i in range N − 1 to 0, decrease by 1, do - curr_val := 0 
-  for j in range i to N, do - curr_val := curr_val * 10 + (s[j] as number) 
-  if curr_val in range 1 through k, then - dp[i] :=(dp[i] + dp[j + 1]) mod m 
 
-  otherwise, - come out from the loop 
 
 
 
- return dp[0] 
Let us see the following implementation to get better understanding −
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] ob = Solution() s = "3456" k = 500 print(ob.solve(s, k))
Input
"3456", 500
Output
7
