Open In App

Python – Factors Frequency Dictionary

Last Updated : 04 May, 2023
Improve
Improve
Like Article
Like
Save
Share
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



Similar Reads

Python | Count the array elements with factors less than or equal to the factors of given x
Given an array, the task is to count the elements of array whose factors are less than the given number x. Examples: Input: arr = [2, 12, 4, 6], x = 6 Output: 2 factors of x = 6 is [1, 2, 3] factors of arr[0] = 2 is [1] factors of arr[1] = 12 is [1, 2, 3, 4] factors of arr[2] = 4 is [1, 2] factors of arr[3] = 6 is [1, 2, 3] so only arr[0] and arr[2
2 min read
Python - Frequency of unequal items in Dictionary
Sometimes, while working with Python, we can come across a problem in which we need to check for the unequal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let’s discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension This particular task
5 min read
Python - Element Frequency starting with K in dictionary value List
Sometimes while working with a lots of data, we can have a problem in which we have data in form of strings list which are values of dictionary keys and we wish to count occurrences of elements starting with character K. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + startswith() This is one way in which thi
5 min read
Python - Convert Frequency dictionary to list
Sometimes, while working with Python dictionaries, we can have a problem in which we need to construct the list out of the values of dictionary. This task is reverse of finding frequency and has application in day-day programming and web development domain. Let's discuss certain ways in which this task can be performed. Input : test_dict = {'gfg' :
4 min read
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 discuss certain ways in which this task can be perform
4 min read
Python - Dictionary List Values Frequency
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the task of computing frequency of all the values in dictionary values lists. This is quite common problem and can have use cases in many domains. Let's discuss certain ways in which this task can be performed. Input : test_dict = {1: ['gfg', 'CS',
6 min read
Python program to find the sum of the value in the dictionary where the key represents the frequency
Given a dictionary with a values list, where the key represents frequency, compute the total occurrence of each value in values lists. Input : test_dict = {70 : [7, 4, 6], 50 : [6, 8, 5, 2]} Output : {7: 70, 4: 70, 6: 120, 8: 50, 5: 50, 2: 50} Explanation : 6 occurs in both keys, hence 70 + 50 = 120, assigned to 6. Input : test_dict = {70 : [7, 4],
3 min read
Python - Cost computation using Frequency and Price dictionary
Given the the price and frequency dictionary, compute total cost of products, i.e. by summing the product of price and frequency of each item. Input : test_dict = {"Apple" : 2, "Mango" : 2, "Grapes" : 2}, {"Apple" : 2, "Mango" : 2, "Grapes" : 2} the put : 12 Explanation : (2*2) + (2*2) + (2*2) = 12. Input : test_dict = {"Apple" : 3, "Mango" : 2, "G
3 min read
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read