Open In App

Python – Retain records with N occurrences of K

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python tuples list, we can have a problem in which we need to perform retention of all the records where occurrences of K is N times. This kind of problem can come in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [(4, 5, 5, 4), (5, 4, 3)], K = 5, N = 2 
Output : [(4, 5, 5, 4)]
Input : test_list = [(4, 5, 5, 4), (5, 4, 3)], K = 5, N = 3 
Output : [] 

Method #1 : Using list comprehension + count() 
The combination of above functions can be used to solve this problem. In this, we perform the task of counting occurrences and conditions and iterations using list comprehension.

Python3




# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using count() + list comprehension
 
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# initializing N
N = 3
 
# Retain records with N occurrences of K
# Using count() + list comprehension
res = [ele for ele in test_list if ele.count(K) == N]
 
# printing result
print("Filtered tuples : " + str(res))


Output : 

The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]

 

Time Complexity: O(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 #2 : Using list comprehension + sum() 
The combination of above functions can be used to solve this problem. In this, we perform the task of computing summation count of K using sum().

Python3




# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using list comprehension + sum()
 
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# initializing N
N = 3
 
# Retain records with N occurrences of K
# Using list comprehension + sum()
res = [ele for ele in test_list if sum(cnt == K for cnt in ele) == N]
 
# printing result
print("Filtered tuples : " + str(res))


Output : 

The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]

 

Time Complexity: O(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 count() + Recursive function

Algorithm: 

  1. Define the recursive function retain_records that takes a list of tuples, a value K, and a value N as input.
  2. If the list is empty, return an empty list.
  3. If the first tuple in the list has N occurrences of K, append it to the result list and call the function recursively with the rest of the list.
  4. If the first tuple in the list does not have N occurrences of K, skip it and call the function recursively with the rest of the list.
  5. Return the result list.

Python3




# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using count() + Recursive function
def retain_records(lst, k, n):
    # Base case: if the list is empty, return an empty list
    if not lst:
        return []
 
    # Recursive case: if the first tuple has N occurrences of K,
    # append it to the result list and call the function recursively
    # with the rest of the list.
    else:
        if lst[0].count(k) == n:
            return [lst[0]] + retain_records(lst[1:], k, n)
        else:
            return retain_records(lst[1:], k, n)
 
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# initializing N
N = 3
 
# Retain records with N occurrences of K
# Using count() +Recursive function
res = retain_records(test_list,K,N)
 
# printing result
print("Filtered tuples : " + str(res))
#this code contributed by tvsk


Output

The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]

Time complexity: O(n), where n is the length of the input list. This is because the function recursively traverses the list once and performs a constant amount of work for each tuple.

Auxiliary space: O(n), where n is the length of the input list. This is because the function creates a new list to store the result tuples, which could be as large as the input list if all tuples meet the filter condition. The recursive call stack also uses O(n) space, as there could be n nested function calls in the worst case.

Method #4: Using operator.countOf() method

  1. Initiated a for loop to traverse the list
  2. Check whether the count of K is equal to N
  3. If yes append that tuple to output list
  4. Display output list

Python3




# Python3 code to demonstrate working of
# Retain records with N occurrences of K
 
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# initializing N
N = 3
 
# Retain records with N occurrences of K
res=[]
import operator
for i in test_list:
    if(operator.countOf(i,K)==N):
        res.append(i)
# printing result
print("Filtered tuples : " + str(res))


Output

The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]

Time Complexity : O(N)
Auxiliary Space : O(N)

Method #5 : Using filter() and lambda():

1.Define a list of tuples test_list.
2.Define the values of K and N.
3.Use the filter() function along with a lambda function to create a new list res of tuples that only contain tuples that have exactly N occurrences of the value K.
4.Convert the filter() object to a list using the list() function and assign it to the variable res.
5.Print out the filtered tuples as a string.

Python3




# Define a list of tuples
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
 
# Define the value of K and N
K = 4
N = 3
# printing original list
print("The original list is : " + str(test_list))
 
# Use the filter() function to create a new list of tuples that only contain tuples that have exactly N occurrences of K
# The lambda function checks how many times K occurs in each tuple x, and returns True if the count is equal to N
# The filter() function returns an iterator, so we convert it to a list with list()
res = list(filter(lambda x: x.count(K) == N, test_list))
 
# Print out the filtered tuples
print("Filtered tuples : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]

Time complexity : O(n * m), where n is the length of the input list test_list and m is the maximum length of a tuple in the list. This is because the filter() function needs to iterate over every tuple in the list, and the count() method needs to iterate over every element in each tuple.
Auxiliary space : O(k), where k is the number of tuples that satisfy the filter condition. This is because the filter() function returns an iterator, and the list() function creates a new list to store the filtered tuples.

Method #6: Using for loop

Algorithm:

  1. Initialize a list of tuples (test_list), and integers K and N.
  2. Create an empty list (res) to store the filtered tuples.
  3. Loop through each tuple (tup) in test_list:
    a. Check if the count of K in tup is equal to N.
    b. If the condition is True, append the tuple to res.
  4. Print the filtered tuples (res).
     

Python3




# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
 
# initializing K
K = 4
 
# initializing N
N = 3
 
# Using for loop
res = []
for tup in test_list:
    if tup.count(K) == N:
        res.append(tup)
 
# printing result
print("Filtered tuples : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]

Time Complexity: O(n * k), where n is the number of tuples in the list and k is the average length of each tuple. This is because we are looping through each tuple in the list and then looping through each element in the tuple to count the occurrences of K.
Auxiliary Space: O(n), where n is the number of tuples in the list. This is because we are storing the filtered tuples in a list (res) which can contain at most n elements.

Method #7: Using filter() and partial() from functools module

Use the filter() method along with the partial() method from the functools module to filter the tuples based on the given conditions.

Step-by-step approach:

  • Import the functools module.
  • Define a function, ‘count_k_in_tuple()‘, that takes in two parameters – k and tuple_t.
  • Inside the function, use the count() method to count the number of times k occurs in tuple_t.
  • If the count is equal to N, return True, else return False.
  • Create a partial function ‘filter_func‘ using the partial() method, where the first argument is count_k_in_tuple() function and the second argument is K.
  • Use the filter() method along with the filter_func and test_list to filter the tuples based on the given conditions.
  • Convert the filtered tuples into a list and assign it to the variable ‘res‘.
  • Print the result.

Below is the implementation of the above approach:

Python3




import functools
 
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
 
# initializing K
K = 4
 
# initializing N
N = 3
 
# define the function to count the number of times k occurs in a tuple
def count_k_in_tuple(k, tuple_t):
    count = tuple_t.count(k)
    if count == N:
        return True
    else:
        return False
 
# create a partial function using the count_k_in_tuple function and the value of K
filter_func = functools.partial(count_k_in_tuple, K)
 
# use the filter function to filter the tuples based on the given conditions
filtered_tuples = filter(filter_func, test_list)
 
# convert the filtered tuples into a list
res = list(filtered_tuples)
 
# print the result
print("Filtered tuples : " + str(res))


Output

Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]

Time complexity: O(N*M), where N is the number of tuples in the list and M is the maximum length of any tuple in the list.
Auxiliary space: O(1) – We are only creating a few variables and not using any additional data structures that depend on the size of the input.



Similar Reads

Python | Retain records of specific length
Sometimes, while working with records, we might desire to filter records in such a way in we need to discard records that do not contain an exact number of elements required to constitute a record. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + len() In this method, we just iterate through the
11 min read
Python | Retain K consecutive elements
Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur K times consecutively. This problem can occur in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using groupby() + list comprehension This task can be performed using above functionalities. In
8 min read
Python | Retain K Front and Rear elements
Sometimes, we require to shrink a list by deletion of its certain elements. One of the methods that is employed to perform this particular task is front and rear element retention and deletion of rest elements. It is a good utility whose solution can be useful to have. Let’s discuss certain ways in which this can be performed. Method #1: Using list
8 min read
Python - Retain K match index values from other list
Sometimes, while working with Python lists, we can have a problem in which we need to retain only the strings with match a particular value from the corresponding list at same index. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip() The combination
9 min read
Python - Retain list elements value items
Sometimes, while working with Python dictionaries, we can have a problem in which we need to retain only those keys, whose values are part of the target list. This kind of problem can have potential problems in many domains including web development. Let's discuss certain ways in which this task can be performed. Input : test_dict = {'gfg': 3} tar_
6 min read
Python - Retain all K elements Rows
Sometimes, while working with Python lists, we can have a problem in which we need to retain rows which have only K as elements. This kind of application can occur in data domains which take Matrix as input. Let's discuss certain ways in which this task can be performed. Input : test_list = [[7, 6], [4, 4], [1, 2], [4]], K = 4 Output : [[4, 4], [4]
8 min read
Python - Retain Numbers in String
Sometimes, while working with Python Strings, we can have a problem in which we need to perform the removal of all the characters other than integers. This kind of problem can have application in many data domains such as Machine Learning and web development. Let's discuss certain ways in which this task can be performed. Input : test_str = 'G4g is
11 min read
Python - Retain first N Elements of a String and Replace the Remaining by K
Given a String, retain first N elements and replace rest by K. Input : test_str = 'geeksforgeeks', N = 5, K = "@" Output : geeks@@@@@@@@ Explanation : First N elements retained and rest replaced by K. Input : test_str = 'geeksforgeeks', N = 5, K = "*" Output : geeks******** Explanation : First N elements retained and rest replaced by K. Method #1 :
6 min read
Python - Retain smallest subsets from strings
Given a set of strings, the task is to write a python program to retain strings from sets that are the smallest possible subset of strings found. Input : test_set = {'cbabca', 'cba', 'bdb', 'bdbab', 'abcx'} Output : {'bdb', 'abcx', 'cba'} Explanation : bdbab is removed as bdb ( smaller subset ) is retained. Input : test_set = {'cbabca', 'cba', 'bdb
2 min read
Python | Convert tuple records to single string
Sometimes, while working with data, we can have a problem in which we have tuple records and we need to change it's to comma-separated strings. These can be data regarding names. This kind of problem has its application in the web development domain. Let's discuss certain ways in which this problem can be solved Method #1: Using join() + list compr
6 min read