Python: Rearrange positive and negative numbers in a given array using Lambda
Python Lambda: Exercise-12 with Solution
Write a Python program to rearrange positive and negative numbers in a given array using Lambda.
Sample Solution:
Python Code :
# Define a list 'array_nums' containing both positive and negative integers
array_nums = [-1, 2, -3, 5, 7, 8, 9, -10]
# Display a message indicating that the following output will show the original array
print("Original arrays:")
print(array_nums) # Print the contents of 'array_nums'
# Use the 'sorted()' function to rearrange the elements in 'array_nums' based on a custom key
# The 'key' parameter uses a lambda function to sort the elements:
# - It places positive numbers before negative numbers and zeros, maintaining their original order
# - Zeros are placed at the front (index 0) of the sorted list
result = sorted(array_nums, key=lambda i: 0 if i == 0 else -1 / i)
# Display the rearranged array where positive numbers come before negative numbers and zeros
print("\nRearrange positive and negative numbers of the said array:")
print(result) # Print the rearranged 'result' array.
Sample Output:
Original arrays: [-1, 2, -3, 5, 7, 8, 9, -10] Rearrange positive and negative numbers of the said array: [2, 5, 7, 8, 9, -10, -3, -1]
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to find intersection of two given arrays using Lambda.
Next: Write a Python program to count the even, odd numbers in a given array of integers using Lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/lambda/python-lambda-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics