- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- 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

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 −

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))

"3456", 500

7

- Related Questions & Answers
- Program to count number of ways we can throw n dices in Python
- Program to count number of unique palindromes we can make using string characters in Python
- Program to find possible number of palindromes we can make by trimming string in Python
- Program to count number of ways we can distribute coins to workers in Python
- Program to find number of ways we can concatenate words to make palindromes in Python
- Program to count number of strings we can make using grammar rules in Python
- Program to find number of ways we can decode a message in Python
- Program to find number of ways we can split a palindrome in python
- Ways to sort list of dictionaries by values in Python
- Python – Sort given list of strings by numeric part of string
- Ways to sort list of dictionaries by values in Python Using itemgetter
- Program to find maximum number of people we can make happy in Python
- Program to find number of ways to split a string in Python
- Program to find maximum number of consecutive values you can make in Python
- Program to count number of ways we can place nonoverlapping edges to connect all nodes in C++

Advertisements