Python Program to get indices of sign change in a list
Last Updated :
10 May, 2023
Given List, the task is to write a python program that extracts all the indices from which sign shift occurred.
Input : test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Output : [1, 4, 6, 7]
Explanation : 6 -> -3, at 1st index, -7 -> 8 at 4th index and so on are shifts.
Input : test_list = [7, 6, -3, -4, -7, 8, 3, 6, 7, 8]
Output : [1, 4]
Explanation : 6 -> -3, at 1st index, -7 -> 8 at 4th index are shifts.
Method 1 : Using loop and conditional statements
In this, we check current and next element to be of opposite signs using conditional statements. Loop is used to iterate through all the elements.
Example:
Python3
# initializing list
test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
res = []
for idx in range(0, len(test_list) - 1):
# checking for successive opposite index
if test_list[idx] > 0 and test_list[idx + 1] < 0 or test_list[idx] < 0 and test_list[idx + 1] > 0:
res.append(idx)
# printing result
print("Sign shift indices : " + str(res))
OutputThe original list is : [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Sign shift indices : [1, 4, 6, 7]
Time Complexity: O(n), The above code iterates through the list once, hence the time complexity is linear, i.e. O(n).
Space Complexity: O(n), The algorithm uses an additional list to store the result, thus consuming linear space which is O(n).
Method 2 : Using list comprehension
Similar to above method, but this provides a one liner alternative using list comprehension.
Example:
Python3
# initializing list
test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to provide one liner alternative
res = [idx for idx in range(0, len(test_list) - 1) if test_list[idx] >
0 and test_list[idx + 1] < 0 or test_list[idx] < 0 and test_list[idx + 1] > 0]
# printing result
print("Sign shift indices : " + str(res))
OutputThe original list is : [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Sign shift indices : [1, 4, 6, 7]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Recursive method.
Step-by-step approach:
- Define a recursive function sign_shift_indices that takes test_list, idx, and res as arguments.
- Check if idx is equal to len(test_list) - 1, if true, then return res.
- Check if the elements at idx and idx+1 in test_list are successive opposites, if true, then append idx to res.
- Call the sign_shift_indices function recursively with incremented idx and updated res.
- In the main program, initialize the test_list and print it.
- Call the sign_shift_indices function with test_list as argument and print the returned result.
Python3
def sign_shift_indices(test_list, idx=0, res=[]):
if idx == len(test_list) - 1:
return res
elif test_list[idx] > 0 and test_list[idx + 1] < 0 or test_list[idx] < 0 and test_list[idx + 1] > 0:
res.append(idx)
return sign_shift_indices(test_list, idx+1, res)
# initializing list
test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
res = sign_shift_indices(test_list)
# printing result
print("Sign shift indices : " + str(res))
OutputThe original list is : [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Sign shift indices : [1, 4, 6, 7]
The time complexity of the recursive function sign_shift_indices is O(n), where n is the length of test_list, since it is traversing the list recursively.
The Auxiliary space is also O(n), because of the space used by the recursive call stack and the list res. Overall time complexity is O(n), and auxiliary space complexity is also O(n).
Method #4: using the built-in zip() function
The zip() function takes two or more iterable objects as input and returns an iterator that aggregates elements from each iterable object.
Step-by-step approach
- Initialize an empty list res to store the indices of sign shifts.
- Use the zip() function to iterate over pairs of adjacent elements in the test_list.
- Use a loop to iterate over the pairs of adjacent elements obtained from zip().
- Check if the signs of the two elements in each pair are opposite (i.e., one is positive and the other is negative).
- If the signs are opposite, append the index of the first element in the pair to res.
- Return the res list containing the indices of sign shift
Python3
# initializing list
test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing result list
res = []
# iterating over pairs of adjacent elements
for idx, (x, y) in enumerate(zip(test_list, test_list[1:])):
# checking for successive opposite index
if x > 0 and y < 0 or x < 0 and y > 0:
# appending the index of the first element in the pair
res.append(idx)
# printing result
print("Sign shift indices : " + str(res))
OutputThe original list is : [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Sign shift indices : [1, 4, 6, 7]
Time complexity: O(n).
Auxiliary space: O(k), where k is the number of sign shifts in the list.
Method #5: Using itertools pairwise() and enumerate()
Step-by-step approach:
- Import the itertools library
- Use the pairwise() function to iterate over the list with two adjacent elements at a time.
- Use enumerate() to get the index of each pair.
- Check if the signs of the two elements are different.
- If the signs are different, append the index to a list.
- Return the list of indices.
Python3
import itertools
def sign_shift_indices(test_list):
res = []
for idx, (a, b) in enumerate(itertools.pairwise(test_list)):
if a * b < 0:
res.append(idx)
return res
# initializing list
test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
# calling the function and measuring time
import time
start = time.time()
res = sign_shift_indices(test_list)
print("Time taken:", time.time()-start)
# printing result
print("Sign shift indices : " + str(res))
Output:
The original list is : [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Sign shift indices : [1, 4, 6, 7]
Time complexity: O(n)
Auxiliary space: O(k), where k is the number of indices where the sign changes.
Similar Reads
Python - Change the signs of elements of tuples in a list
Given a dual Tuple list, the task is to write a python program to convert second element to negative magnitude of each tuple and first element to positive magnitude of each tuple. Input : test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)] Output : [(3, -1), (4, -3), (1, -3), (2, -5)
3 min read
Python program to find the Decreasing point in List
Given a list, get the index of element where the list shows the first negative trend, i.e first point where the next element < current element. If not found return -1. Input : test_list = [3, 6, 8, 9, 12, 5, 18, 1] Output : 4 Explanation : At 12 -> 5, first decreasing point occurs. Input : tes
4 min read
Python program to create a list centered on zero
Given two integer variables, limit and diff, write a Python program to create a list that is centered on zero, using limit, which specifies limit of the list and diff that specifies the common difference between integers. Examples: Input : limit = 1, diff = 0.5 Output : [-1, -0.5, 0.0, 0.5, 1] Input
3 min read
Python program to interchange first and last elements in a list
Given a list, write a Python program to swap the first and last element of the list using Python.Examples: The last element of the list can be referred to as a list[-1]. Therefore, we can simply swap list[0] with list[-1].Python# Initialize a list my_list = [1, 2, 3, 4, 5] # Interchange first and la
5 min read
Python | Get indices of True values in a binary list
Boolean lists are often used by developers to check for True values during hashing. The boolean list is also used in certain dynamic programming paradigms in dynamic programming. Let's discuss certain ways to get indices of true values in a list in Python. Method #1 : Using enumerate() and list comp
9 min read
Get the indices of all occurrences of an element in a list - Python
We are given a list and our task is to find all the indices where a particular element occurs. For example, if we have a list like [1, 2, 3, 2, 4, 2] and the element is 2, then the output will be [1, 3, 5] because 2 appears at these positions.Using List ComprehensionList comprehension allows for a c
2 min read
Python program to find sum of absolute difference between all pairs in a list
Given a list of distinct elements, write a Python program to find the sum of absolute differences of all pairs in the given list.Examples: Input : [9, 2, 14] Output : 24 Explanation: (abs(9-2) + abs(9-14) + abs(2-14)) Input : [1, 2, 3, 4] Output : 10 Explanation: (abs(1-2) + abs(1-3) + abs(1-4) + ab
5 min read
Python program to Test if all y occur after x in List
Given a List, test if all occurrences of y are after the occurrence of x in the list. Input : test_list = [4, 5, 6, 2, 4, 5, 2, 9], x, y = 6, 2 Output : True Explanation : All occurrences of 2 are after 6, hence true. Input : test_list = [4, 2, 5, 6, 2, 4, 5, 2, 9], x, y = 6, 2 Output : False Explan
4 min read
Python - Indices of atmost K elements in list
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 min read
Python - Change type of key in Dictionary list
Sometimes, while working with data, we can have a problem in which we require to change the type of particular keys' value in list of dictionary. This kind of problem can have application in data domains. Lets discuss certain ways in which this task can be performed. Input : test_list = [{'gfg': 9,
6 min read