- 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
A number and its triple in Python
Suppose we have a list of numbers called nums, we have to check whether there are two numbers such that one is a triple of another or not.
So, if the input is like nums = [2, 3, 10, 7, 9], then the output will be True, as 9 is the triple of 3
To solve this, we will follow these steps −
i := 0
sort the list n
j := 1
while j < size of n, do
if 3*n[i] is same as n[j], then
return True
if 3*n[i] > n[j], then
j := j + 1
otherwise,
i := i + 1
return False
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): i = 0 n.sort() j = 1 while (j < len(n)): if (3*n[i] == n[j]): return True if (3*n[i] > n[j]): j += 1 else: i += 1 return False ob = Solution() print(ob.solve([2, 3, 10, 7, 9]))
Input
[2, 3, 10, 7, 9]
Output
True
Advertisements