import math def is_prime(n): if n == 1 or n == 0: return False if n == 2: return True if n%2 == 0: return False for i in range(3, math.ceil(math.sqrt(n))): if n%i == 0: return False return True def filter_function(elem, hash_b): if elem not in hash_b: return True return not is_prime(hash_b[elem]) def solution(a, b): hash_b = {} for elem in b: if elem in hash_b: hash_b[elem] += 1 else: hash_b[elem] = 1 print(hash_b) c = [elem for elem in a if filter_function(elem, hash_b)] return c a = [2,3,9,2,5,1,3,7,10] b = [2,1,3,4,3,10,6,6,1,7,10,10,10] print(solution(a, b))