
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
K and -K in Python
Suppose we have a list of numbers called nums, we have to find the largest number k where k and -k both exist in nums (they can be the same number). If there's no such element, return -1.
So, if the input is like [-5, 2, 9, -6, 5, -9], then the output will be 9.
To solve this, we will follow these steps −
- L1:= a list of 0 and positive elements in nums
- L2:= a list of 0 and negative elements in nums
- sort L1 in reverse order
- sort the list L2
- for each i in L1, do
- for each j in L2, do
- if i+j is same as 0, then
- return i
- otherwise when i+j > 0 , then
- come out from the current loop
- if i+j is same as 0, then
- for each j in L2, do
- return -1
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): L1=[i for i in nums if i>=0] L2=[i for i in nums if i<=0] L1.sort(reverse=True) L2.sort() for i in L1: for j in L2: if i+j==0: return i elif i+j>0: break return -1 ob = Solution() nums = [-5, 2, 9, -6, 5, -9] print(ob.solve(nums))
Input
[-5, 2, 9, -6, 5, -9]
Output
9
- Related Articles
- On converting 25°C, 38°C and 66°C to Kelvin scale, the correct sequence of temperatures will be :(a) 298 K, 311 K and 339 K (b) 298 K, 300 K and 338 K(c) 273 K, 278 K and 543 K (d) 298 K, 310 K and 338 K
- On converting 25°C, 38°C and 66°C to kelvin scale, the correct sequence of temperature will be(a) 298 K, 311 K and 339 K(b) 298 K, 300 K and 338 K(c) 273 K, 278 K and 543 K(d) 298 K, 310 K and 338 K
- Program to find k where k elements have value at least k in Python
- K Prefix in Python
- Find the value (s) of $k$ for which the points $(3k – 1, k – 2), (k, k – 7)$ and $(k – 1, -k – 2)$ are collinear.
- Find the values of \( k \) if the points \( \mathrm{A}(k+1,2 k), \mathrm{B}(3 k, 2 k+3) \) and \( \mathrm{C}(5 k-1,5 k) \) are collinear.
- Python – K middle elements
- Find smallest number K such that K % p = 0 and q % K = 0 in C++
- Top K Frequent Elements in Python
- List expansion by K in Python
- Merge k Sorted Lists in Python
- Maximum and Minimum K elements in Tuple using Python
- Program to find smallest value of K for K-Similar Strings in Python
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- Determine \( k \) so that \( k^{2}+4 k+8,2 k^{2}+3 k+6,3 k^{2}+4 k+4 \) are three consecutive terms of an AP.

Advertisements