![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Find Out the Probability of Having n or Fewer Points in Python
Suppose we are playing a unique game and we have three values n, k, and h. We start from 0 points, then we can select a number randomly between 1 and h (inclusive) and we will get that many points. We stop when we have scored a minimum of k points. We have to find the probability that we have n or fewer points. Here any number can be chosen randomly and the outcomes all have the same probability.
So, if the input is like n = 2, k = 2, h = 10, then the output will be 0.11.
To solve this, we will follow these steps −
Define a function dp() . This will take path.
if path is same as k − 1, thens
return (minimum of n − k + 1 and h) / h
if path > n, then
return 0
if path >= k, then
return 1
return dp(path + 1) − (dp(path + h + 1) − dp(path + 1)) / h
From the main function, do the following −
if k is zero, then
return 1
if n < k , then
return 0
return dp(0)
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n, k, h): if not k: return 1 if n < k: return 0 def dp(path): if path == k− 1: return min((n− k + 1), h) / h if path > n: return 0 if path >= k: return 1 return dp(path + 1)− (dp(path + h + 1)− dp(path + 1)) / h return dp(0) ob = Solution() print(ob.solve(2,2,10))
Input
2,2,10
Output
0.11