Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Sort Matrix Rows by summation of consecutive difference of elements
Next article icon

Python Program to Sort Matrix by Sliced Row and Column Summation

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Matrix and a range of indices, the task is to write a python program that can sort a matrix on the basis of the sum of only given range of indices of each row and column i.e. the rows and columns are to sliced from a given start to end index, further, matrix are sorted using only those slices sum from each row or column.

Input : test_list = [[1, 4, 3, 1, 3], [3, 4, 5, 2, 4], [23, 5, 5, 3], [2, 3, 5, 1, 6]], i, j = 1, 3 
Output : [[1, 4, 3, 1, 3], [2, 3, 5, 1, 6], [3, 4, 5, 2, 4], [23, 5, 5, 3]] 
Explanation : 7 < 8 < 9 < 10, is summation of 1st and 2nd element.

Input : test_list = [[1, 4, 3, 1, 3], [23, 5, 5, 3], [2, 3, 5, 1, 6]], i, j = 1, 3 
Output : [[1, 4, 3, 1, 3], [2, 3, 5, 1, 6], [23, 5, 5, 3]] 
Explanation : 7 < 8 < 10, is summation of 1st and 2nd element. 

Summation on rows

Method 1 : Using sort(), slice and sum()

In this, we perform the task of in-place sorting using sort(), and summation is done using sum(), slice operation is done using list slicing, which together forms as key function for sorting.

Example:

Python3




# get sliced summation
def get_sliced_sum(row):
    return sum(row[i:j])
 
 
# initializing list
test_list = [[1, 4, 3, 1, 3], [3, 4, 5, 2, 4],
             [23, 5, 5, 3], [2, 3, 5, 1, 6]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing range
i, j = 1, 3
 
# performing sort
test_list.sort(key=get_sliced_sum)
 
# printing result
print("Sorted List : " + str(test_list))
 
 

Output:

The original list is : [[1, 4, 3, 1, 3], [3, 4, 5, 2, 4], [23, 5, 5, 3], [2, 3, 5, 1, 6]]

Sorted List : [[1, 4, 3, 1, 3], [2, 3, 5, 1, 6], [3, 4, 5, 2, 4], [23, 5, 5, 3]]

Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(1)

Method 2 : Using sorted(), lambda, sum() and slicing 

In this, the task of performing sort is done using sorted() and lambda function is used to get a summation of sliced rendered using one-statement without external function call.

Example:

Python3




# initializing list
test_list = [[1, 4, 3, 1, 3], [3, 4, 5, 2, 4],
             [23, 5, 5, 3], [2, 3, 5, 1, 6]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing range
i, j = 1, 3
 
# performing sort using sorted()
# filter util. using lambda fnc.
res = sorted(test_list, key=lambda row: sum(row[i:j]))
 
# printing result
print("Sorted List : " + str(res))
 
 

Output:

The original list is : [[1, 4, 3, 1, 3], [3, 4, 5, 2, 4], [23, 5, 5, 3], [2, 3, 5, 1, 6]]

Sorted List : [[1, 4, 3, 1, 3], [2, 3, 5, 1, 6], [3, 4, 5, 2, 4], [23, 5, 5, 3]]

The time complexity of this approach is O(nlogn), where n is the number of sublists in the input list.
The auxiliary space complexity of this approach is O(n), where n is the number of sublists in the input list.

Method 3:  Using the built-in map() and lambda functions 

Step-by-step approach: 

  • Define a nested list test_list with 4 sublists each containing 4 elements.
  • Print the original list test_list.
  • Define two variables i and j with values 1 and 3 respectively.
  • Use map() and lambda to extract sublists from test_list using slice indices i and j, then compute the sum of each sublist.
  • Convert the resulting map object into a list of sums using the list() function.
  • Use the zip() function to combine each sum with its corresponding sublist from test_list.
  • Sort the resulting list of tuples by the sums using sorted() function and a lambda function to specify the sorting key.
  • Use a list comprehension to extract the sorted sublists from the sorted list of tuples.
  • Print the sorted list of sublists res.

Below is the implementation of the above approach:

Python3




# initializing list
test_list = [[1, 4, 3, 1], [3, 4, 5, 2], [23, 5, 5, 3], [2, 3, 5, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing range
i, j = 1, 3
 
# extracting sublists and computing sums using map() and lambda
sums = list(map(lambda x: sum(x[i:j]), test_list))
 
# sorting original list by computed sums
res = [x for _, x in sorted(zip(sums, test_list))]
 
# printing result
print("Sorted List Columnwise : " + str(res))
 
 
Output
The original list is : [[1, 4, 3, 1], [3, 4, 5, 2], [23, 5, 5, 3], [2, 3, 5, 1]] Sorted List Columnwise : [[1, 4, 3, 1], [2, 3, 5, 1], [3, 4, 5, 2], [23, 5, 5, 3]]

Time complexity: O(n log n) – sorting the list takes O(n log n) time
Auxiliary space: O(n) – we use a list to store the computed sums

Summation on column

Method 1 : Using sort(), slice and sum()

In this, we perform transpose of a base matrix and then perform the usual task of getting slice using above method 1, after sorting, the matrix is again converted to its transposed format. 

Example:

Python3




# get sliced summation
def get_sliced_sum(row):
    return sum(row[i:j])
 
 
# initializing list
test_list = [[1, 4, 3, 1], [3, 4, 5, 2],
             [23, 5, 5, 3], [2, 3, 5, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing range
i, j = 1, 3
 
# transposing matrix
test_list = list(zip(*test_list))
 
# performing sort
test_list.sort(key=get_sliced_sum)
 
# performing transpose again to get
# result.
test_list = zip(*test_list)
 
# converting list of tuples to list of
# lists
res = [list(sub) for sub in test_list]
 
# printing result
print("Sorted List Columnwise : " + str(res))
 
 

Output:

The original list is : [[1, 4, 3, 1], [3, 4, 5, 2], [23, 5, 5, 3], [2, 3, 5, 1]]

Sorted List Columnwise : [[1, 4, 3, 1], [2, 4, 5, 3], [3, 5, 5, 23], [1, 3, 5, 2]]

Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(k)

Method 2 : Using sorted(), lambda, sum() and slicing 

In this, we perform transpose of a base matrix and then perform the usual task of getting slice using above method 2, after sorting, the matrix is again converted to its transposed format. 

Example:

Python3




# initializing list
test_list = [[1, 4, 3, 1], [3, 4, 5, 2],
             [23, 5, 5, 3], [2, 3, 5, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing range
i, j = 1, 3
 
# transposing matrix
test_list = zip(*test_list)
 
# performing sort using sorted()
# filter util. using lambda fnc.
res = sorted(test_list, key=lambda row: sum(row[i:j]))
 
# performing transpose again to get result.
res = zip(*res)
 
# converting list of tuples to list of lists
res = [list(sub) for sub in res]
 
# printing result
print("Sorted List Columnwise : " + str(list(res)))
 
 

Output:

The original list is : [[1, 4, 3, 1], [3, 4, 5, 2], [23, 5, 5, 3], [2, 3, 5, 1]]

Sorted List Columnwise : [[1, 4, 3, 1], [2, 4, 5, 3], [3, 5, 5, 23], [1, 3, 5, 2]]

Method 3: using list comprehension and lambda function. Here are the steps for this approach:

Step-by-step approach:

  1. Transpose the given list of lists using zip(*test_list).
  2. Use list comprehension to create a list of tuples where each tuple contains a column from the transposed list and the sliced summation of that column.
  3. Sort the list of tuples based on the sliced summation using the lambda function.
  4. Transpose the sorted list of tuples using zip(*sorted_list).
  5. Convert the list of tuples to a list of lists.

Below is the implementation of the above approach:

Python3




# get sliced summation
def get_sliced_sum(row, i, j):
    return sum(row[i:j])
 
# initializing list
test_list = [[1, 4, 3, 1], [3, 4, 5, 2], [23, 5, 5, 3], [2, 3, 5, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing range
i, j = 1, 3
 
# transposing matrix
test_list_transposed = list(zip(*test_list))
 
# creating list of tuples with sliced summation
sorted_list = [(col, get_sliced_sum(col, i, j)) for col in test_list_transposed]
 
# sorting the list of tuples based on sliced summation
sorted_list.sort(key=lambda x: x[1])
 
# transposing the sorted list of tuples
sorted_list_transposed = list(zip(*sorted_list))
 
# converting list of tuples to list of lists
result = [list(sub) for sub in sorted_list_transposed]
 
# printing result
print("Sorted List Columnwise : " + str(result))
 
 
Output
The original list is : [[1, 4, 3, 1], [3, 4, 5, 2], [23, 5, 5, 3], [2, 3, 5, 1]] Sorted List Columnwise : [[(1, 2, 3, 1), (4, 4, 5, 3), (3, 5, 5, 5), (1, 3, 23, 2)], [5, 9, 10, 26]]

Time complexity: O(mnlog(n)), where m is the number of rows and n is the number of columns in the original list. This is because the list is transposed and sorted based on the sliced summation of each column using the sorted() function, which has a time complexity of O(n*log(n)).

Auxiliary space: O(m*n), where m is the number of rows and n is the number of columns in the original list. This is because the transposed list and the list of tuples with sliced summation are stored in memory during the execution of the program.



Next Article
Python Program to Sort Matrix Rows by summation of consecutive difference of elements
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python Program to Sort the matrix row-wise and column-wise
    Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.Examples: Input : mat[][] = { {4, 1, 3}, {9, 6, 8}, {5, 2, 7} } Output : 1 3 4 2 5 7 6 8 9 Input : mat[][] = { {12, 7, 1, 8}, {20, 9, 11, 2}, {15, 4, 5, 13}, {3, 18, 10, 6} } Output : 1 5 8 12 2 6 10 15 3 7 11 18 4 9 13
    4 min read
  • Python program to sort matrix based upon sum of rows
    Given a Matrix, perform sort based upon the sum of rows. Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 3 < 9 < 11 < 14. Sorted sum. Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]] Output : [[4, 5], [4, 6, 1], [2,
    6 min read
  • Python Program to Sort Matrix Rows by summation of consecutive difference of elements
    Given a Matrix, the following article depicts how to sort rows of a matrix on the basis of summation of difference between consecutive elements of a row. Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], Output : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]] Ex
    7 min read
  • Python Program to sort rows of a matrix by custom element count
    Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 < 1 = 1 < 3 i
    5 min read
  • Python program to Sort Matrix by Maximum Row element
    Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
    4 min read
  • Python Program to Find median in row wise sorted matrix
    We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples: Input : 1 3 5 2 6 9 3 6 9Output : Median is 5If we put all the values in a sorted array A[] = 1 2 3 3 5 6 6 9 9)Input: 1 3 4 2 5 6 7 8 9Output: Median is
    5 min read
  • Python Program to Sort Matrix Rows According to Primary and Secondary Indices
    Given Matrix, the task here is to write a Python program to sort rows based on primary and secondary indices. First using primary indices the rows will be arranged based on the element each row has at the specified primary index. Now if two rows have the same element at the given primary index, sort
    3 min read
  • Python Program to Sort the given matrix
    Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i <= n-1, first element of row 'i' is greater than or equal to the la
    4 min read
  • Python - Summation of kth column in a matrix
    Sometimes, while working with Python Matrix, we may have a problem in which we require to find the summation of a particular column. This can have a possible application in day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Us
    8 min read
  • Python program to a Sort Matrix by index-value equality count
    Given a Matrix, the task is to write a Python program that can sort its rows or columns on a measure of the number of values equal to its index number. For each row or column, count occurrences of equality of index number with value. After computation of this count for each row or column, sort the m
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences