- 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
Check if all sub-numbers have distinct Digit product in Python
Suppose we have a number n, we have to check whether all sub-numbers of this number have unique digit product or not. As we know, n digit number has n*(n+1)/2 sub-numbers. For example, the sub-numbers of 135 are 1, 3, 5, 13, 35, 135. And the digit product of a number is product of its digits.
So, if the input is like n = 235, then the output will be True as sub numbers are [2, 3, 5, 23, 35, 235], digit products are [2, 3, 5, 6, 15, 30]
To solve this, we will follow these steps −
Define a function dig_prod() . This will take digits
- product := 1
- for each d in digits, do
- product := product * d
- return product
- From the main method do the following:
- num_str := num as string
- length := size of num_str
- digits := a list of size length, and initially all values are null
- prod_set := a new empty set
- for i in range 0 to length, do
- digits[i] := num_str[i] as integer
- for i in range 0 to length - 1, do
- for j in range i to length - 1, do
- item := dig_prod(digits[from index i to j])
- if item is in prod_set, then
- return False
- otherwise,
- insert item into prod_set
- for j in range i to length - 1, do
- return True
Let us see the following implementation to get better understanding −
Example
def dig_prod(digits): product = 1 for d in digits: product *= d return product def solve(num): num_str = str(num) length = len(num_str) digits = [None] * length prod_set = set() for i in range(0, length): digits[i] = int(num_str[i]) for i in range(0, length): for j in range(i, length): item = dig_prod(digits[i:j+1]) if item in prod_set: return False else: prod_set.add(item) return True n = 235 print(solve(n))
Input
235
Output
True
Advertisements