 
  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 throw n dices in Python
Suppose we have a number n, number of faces, and a total value, we have to find the number of ways it is possible to throw n dice with faces each to get total. If the answer is very large mod the result by 10**9 + 7.
So, if the input is like n = 2 faces = 6 total = 8, then the output will be 5, as there are 5 ways to make 8 with 2 6-faced dice: (2 and 6), (6 and 2), (3 and 5), (5 and 3), (4 and 4).
To solve this, we will follow these steps −
- m := 10^9 + 7 
- dp := a list of size (total + 1) then fill with 0 
-  for face in range 1 to minimum of faces, update in each step by total + 1, do - dp[face] := 1 
 
-  for i in range 0 to n - 2, do - for j in range total to 0, decrease by 1, do 
- dp[j] := sum of all dp[j - f] for f in range 1 to faces + 1 when j - f >= 1 
 
- return last element of dp mod m 
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n, faces, total): m = 10 ** 9 + 7 dp = [0] * (total + 1) for face in range(1, min(faces, total) + 1): dp[face] = 1 for i in range(n - 1): for j in range(total, 0, -1): dp[j] = sum(dp[j - f] for f in range(1, faces + 1) if j - f >= 1) return dp[-1] % m ob = Solution() n = 2 faces = 6 total = 8 print(ob.solve(n, faces, total))
Input
2,6,8
Output
5
