
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Largest Number by Two Times in Python
Suppose we have a list of numbers; we have to check whether the largest number is bigger than the second-largest number by more than two times. As an example, if the list is like [3, 9, 6], then it will return false, as 9 is not bigger than 12 (2 times 6). When the list is [6, 3, 15], it will return true, as 15 is bigger than 12 (2 times 6).
To solve this, we will follow these steps −
- if size of nums < 2, then
- return False
- p_max := minimum of nums[0] and nums[1]
- c_max := maximum of nums[0] and nums[1]
- for i in range 2 to size of nums, do
- if nums[i] > p_max, then
- if nums[i] > c_max, then
- p_max := c_max
- c_max := nums[i]
- otherwise,
- p_max := nums[i]
- if nums[i] > c_max, then
- if nums[i] > p_max, then
- return c_max > p_max * 2
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): if len(nums) < 2: return False p_max = min(nums[0], nums[1]) c_max = max(nums[0], nums[1]) for i in range(2, len(nums)): if nums[i] > p_max: if nums[i] > c_max: p_max = c_max c_max = nums[i] else: p_max = nums[i] return c_max > p_max * 2 ob = Solution() nums = [3,6,15] print(ob.solve(nums))
Input
[3,6,15]
Output
None
Advertisements