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 - Sort Matrix by Palindrome count
Next article icon

Python – Sort by Factor count

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

Given element list, sort by factor count of each element.

Input : test_list = [12, 100, 22] 
Output : [22, 12, 100] 
Explanation : 3, 5, 8 factors respectively of elements.

Input : test_list = [6, 11] 
Output : [11, 6] 
Explanation : 1, 4 factors respectively of elements. 

Method #1 : Using sort() + len() + list comprehension

In this, we perform task of sorting using sort(), and len() and list comprehension is used for task of getting the count of factors.

Python3




# Python3 code to demonstrate working of
# Sort by Factor count
# Using sort() + len() + list comprehension
 
 
def factor_count(ele):
 
    # getting factors count
    return len([ele for idx in range(1, ele) if ele % idx == 0])
 
 
# initializing list
test_list = [12, 100, 360, 22, 200]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sort
test_list.sort(key=factor_count)
 
# printing result
print("Sorted List : " + str(test_list))
 
 

 Output:

The original list is : [12, 100, 360, 22, 200] Sorted List : [22, 12, 100, 200, 360]

Time Complexity: O(nlogn) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(1) additional space is not needed

Method #2 : Using lambda + sorted() + len()

In this, task of sorting is done using sorted(), and lambda function is used to feed to sorted to get factors.

Python3




# Python3 code to demonstrate working of
# Sort by Factor count
# Using lambda + sorted() + len()
 
# initializing list
test_list = [12, 100, 360, 22, 200]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sort using sorted(), lambda getting factors
res = sorted(test_list, key=lambda ele: len(
    [ele for idx in range(1, ele) if ele % idx == 0]))
 
# printing result
print("Sorted List : " + str(res))
 
 

Output:

The original list is : [12, 100, 360, 22, 200] Sorted List : [22, 12, 100, 200, 360] 

Method #3: Using a dictionary to store factor counts and sort by value

Algorithm:

Define an empty dictionary factor_counts.
Iterate over the elements of the input list test_list and for each element ele:
a. Define a variable count to store the number of factors of ele.
b. Iterate over the range from 1 to ele, inclusive, and increment count for each factor of ele.
c. Add a key-value pair to factor_counts with key ele and value count.
Sort test_list by factor count using the factor_counts dictionary. To do this, pass a lambda function to the sorted() function as the key parameter, which returns the value of the corresponding key-value pair in factor_counts for each element in test_list.
Return the sorted list.

Python3




# Python3 code to demonstrate working of
# Sort by Factor count
# Using a dictionary to store factor counts and sort by value
 
# initializing list
test_list = [12, 100, 360, 22, 200]
 
# printing original list
print("The original list is : " + str(test_list))
 
# defining an empty dictionary to store factor counts
factor_counts = {}
 
# iterating over the elements of the input list and storing factor counts in the dictionary
for ele in test_list:
    count = 0
    for idx in range(1, ele + 1):
        if ele % idx == 0:
            count += 1
    factor_counts[ele] = count
 
# sorting the list by factor count using the dictionary
res = sorted(test_list, key=lambda ele: factor_counts[ele])
 
# printing result
print("Sorted List : " + str(res))
 
 
Output
The original list is : [12, 100, 360, 22, 200] Sorted List : [22, 12, 100, 200, 360] 

Time complexity: O(n^2), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list. 



Next Article
Python - Sort Matrix by Palindrome count
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Sort Matrix by Palindrome count
    Given a String Matrix of N characters, sort each row by the count of the palindromic string in it. Input : test_list = [["nitin", "meem", "geeks"], ["peep"], ["gfg", "is", "best"], ["sees", "level", "mom", "noon"]] Output : [['peep'], ['gfg', 'is', 'best'], ['nitin', 'meem', 'geeks'], ['sees', 'leve
    8 min read
  • Counting Sort - Python
    Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
    7 min read
  • Sort a Dictionary - Python
    In Python, dictionaries store key-value pairs and are great for organizing data. While they weren’t ordered before Python 3.7, you can still sort them easily by keys or values, in ascending or descending order. Whether you’re arranging names alphabetically or sorting scores from highest to lowest, P
    5 min read
  • Python Program for Counting Sort
    Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. C/C++ Code # Python program for counting s
    2 min read
  • Sort Python Dictionary by Value
    Python dictionaries are versatile data structures that allow you to store key-value pairs. While dictionaries maintain the order of insertion. sorting them by values can be useful in various scenarios. In this article, we'll explore five different methods to sort a Python dictionary by its values, a
    3 min read
  • Python - Sort Dictionaries by Size
    Given a Dictionary List, perform sort by size of dictionary. Input : test_list = [{4:6, 9:1, 10:2, 2:8}, {4:3, 9:1}, {3:9}, {1:2, 9:3, 7:4}] Output : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}] Explanation : 1 < 2 < 3 < 4, sorted by number of keys of dictionary. In
    4 min read
  • Sort a list in python
    Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting. [GFGTABS] Python # Initializing a list a = [5, 1, 5, 6] # Sort modifies the given list a.sort() print(a) b = [5, 2, 9, 6] # Sorted does not m
    5 min read
  • Python - Sort Matrix by None frequency
    In the world of Python programming, many developers aim to make matrix operations efficient and elegant in their code. A fascinating challenge that comes up is sorting a matrix based on how often the mysterious "None" element appears, adding an interesting twist to data manipulation in Python. Given
    9 min read
  • Python - Sort Matrix by total characters
    Given a String Matrix, sort by total data, i.e total characters in each row. Input : test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"], ["ILvGFG"]] Output : [['ILvGFG'], ['Gfg', 'is', 'Best'], ['Geeksforgeeks', 'Best']] Explanation : 6 < 11 < 17 total characters respectively after
    5 min read
  • Sort List Elements by Frequency - Python
    Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
    3 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