Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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 - Factors Frequency Dictionary
Next article icon

Python - Factors Frequency Dictionary

Last Updated : 04 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list with elements, construct a dictionary with frequency of factors.

Input : test_list = [2, 4, 6, 8] Output : {1: 4, 2: 4, 3: 1, 4: 2, 5: 0, 6: 1, 7: 0, 8: 1} Explanation : All factors count mapped, e.g 2 is divisible by all 4 values, hence mapped with 4. Input : test_list = [1, 2] Output : {1: 2, 2 : 1} Explanation : Similar as above, 1 is factor of all.

Method #1 : Using loop 

 This is brute way in which this task can be performed. In this, the elements are iterated and required number is checked for being a factor, if yes, its frequency is increased in dictionary corresponding to its key.

Python3
# Python3 code to demonstrate working of  # Factors Frequency Dictionary # Using loop  # initializing list test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]  # printing original list print("The original list : " + str(test_list))  res = dict()  # iterating till max element  for idx in range(1, max(test_list)):     res[idx] = 0     for key in test_list:                  # checking for factor          if key % idx == 0:             res[idx] += 1          # printing result  print("The constructed dictionary : " + str(res)) 

Output
The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18] The constructed dictionary : {1: 10, 2: 7, 3: 6, 4: 4, 5: 1, 6: 3, 7: 0, 8: 2, 9: 2, 10: 0, 11: 0, 12: 1, 13: 0, 14: 0, 15: 1, 16: 1, 17: 0}

Time Complexity: O(n*n), where n is the elements of dictionary
Auxiliary Space: O(n), where n is the size of dictionary

Method #2 : Using sum() + loop

This is almost similar approach to above problem. The difference being sum() is used for summation rather than a manual loop for solving problem. 

Python3
# Python3 code to demonstrate working of  # Factors Frequency Dictionary # Using sum() + loop  # initializing list test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]  # printing original list print("The original list : " + str(test_list))  res = dict() for idx in range(1, max(test_list)):          # using sum() instead of loop for sum computation     res[idx] = sum(key % idx == 0 for key in test_list)  # printing result  print("The constructed dictionary : " + str(res)) 

Output
The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18] The constructed dictionary : {1: 10, 2: 7, 3: 6, 4: 4, 5: 1, 6: 3, 7: 0, 8: 2, 9: 2, 10: 0, 11: 0, 12: 1, 13: 0, 14: 0, 15: 1, 16: 1, 17: 0}

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”. 

Method #3: Using collections.Counter() and itertools.chain()

Import the collections module.
Initialize a dictionary res with all the keys as integers from 1 to the maximum value in the test_list.
Convert the test_list into a list of factors using a nested list comprehension.
Flatten the list of factors into a single list using the itertools.chain() method.
Count the frequency of each factor using the collections.Counter() method and store the result in res.
Print the resulting dictionary res.

Python3
import collections import itertools  # initializing list test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]  # printing original list print("The original list : " + str(test_list))  # using collections.Counter() and itertools.chain() to construct frequency dictionary res = {i: collections.Counter(itertools.chain(*[[j for j in range(1, i+1) if key % j == 0] for key in test_list]))[i] for i in range(1, max(test_list)+1)}  # printing result print("The constructed dictionary : " + str(res)) 

Output
The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18] The constructed dictionary : {1: 10, 2: 7, 3: 6, 4: 4, 5: 1, 6: 3, 7: 0, 8: 2, 9: 2, 10: 0, 11: 0, 12: 1, 13: 0, 14: 0, 15: 1, 16: 1, 17: 0, 18: 1}

The time complexity O(n^2), where n is the length of the test_list.
 The auxiliary space  O(n^2), since we are creating a list of factors for each element in test_list, and then flattening it into a single list.

Method #4 : Using list(),set() and count() methods

Approach

  1. Find the factors of each number of test_list using nested for loops and append them to an empty list x
  2. Remove the duplicates from x using list(),set() and store it in y, create an empty dictionary res
  3. Initiate a for loop over list y and initialise the dictionary with elements of y as keys and count of these elements in x as values
  4. Display res
Python3
# Python3 code to demonstrate working of # Factors Frequency Dictionary # Using loop  # initializing list test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]  # printing original list print("The original list : " + str(test_list))   # iterating till max element x=[] for i in range(1, max(test_list)):     for key in test_list:         if key % i == 0:             x.append(i) y=list(set(x)) res=dict() for i in y:     res[i]=x.count(i)      # printing result print("The constructed dictionary : " + str(res)) 

Output
The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18] The constructed dictionary : {1: 10, 2: 7, 3: 6, 4: 4, 5: 1, 6: 3, 8: 2, 9: 2, 12: 1, 15: 1, 16: 1}

Time Complexity : O(M*N) M - length of range 1 to max(test_list) N - length of test_list

Auxiliary Space : O(N) N - length of res dictionary


Next Article
Python - Factors Frequency Dictionary

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

    Python - Frequency Grouping Dictionary
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the grouping of dictionary data, in a way in which we need to group all the similar dictionaries key with its frequency. This kind of problem has its application in web development domain. Let's disc
    4 min read
    Python - Convert Frequency dictionary to list
    When we convert a frequency dictionary to a list, we are transforming the dictionary into a list of key-value or just the keys/values, depending on needs. We can convert a frequency dictionary to a list using methods such as list comprehension, loops, extend() method and itertools.chain() function.F
    3 min read
    Python Iterate Dictionary Key, Value
    In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
    3 min read
    Python - Values frequency across Dictionaries lists
    Given two list of dictionaries, compute frequency corresponding to each value in dictionary 1 to second. Input : test_list1 = [{"Gfg" : 6}, {"best" : 10}], test_list2 = [{"a" : 6}, {"b" : 10}, {"d" : 6}}] Output : {'Gfg': 2, 'best': 1} Explanation : 6 has 2 occurrence in 2nd list, 10 has 1. Input :
    6 min read
    Python - Dictionary Values Mean
    Given a dictionary, find the mean of all the values present. Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. Input : test_dict = {"Gfg" : 5, "is" : 10, "Best" : 15} Output : 10.0 Explanation : Mean of
    4 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