Last active
January 29, 2020 19:10
-
-
Save RadoslawB/bc6bf05b4121ba7f11f61c320fcb1b69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import List, Any, Dict | |
from collections import Counter | |
""" | |
Write a function that receives two sequences: A and B of integers and returns one sequence C. | |
Sequence C should contain all elements from sequence A (maintaining the order) except those, | |
that are present in sequence B p times, where p is a prime number. | |
""" | |
def is_prime(n: int) -> bool: | |
""" | |
O(n/2) -> O(n) coplexity | |
""" | |
if n == 2 or n == 3: return True | |
if n % 2 == 0 or n < 2: return False | |
# only odd numbers. | |
# Internet says that you have to loop over up to sqrt(n) but I didnt dig | |
# in why it is true so played safe here and loop over up to n/2. | |
for i in range(3, int(n / 2) + 1, 2): | |
if n % i == 0: | |
return False | |
return True | |
def get_prime_number_of_occurances_of_values_in_collection(collection: List[Any]) -> Dict[Any, bool]: | |
values_count = dict(Counter(collection)) | |
result_dict = {} | |
for key, value in values_count.items(): | |
if is_prime(value): | |
result_dict[key] = True | |
return result_dict | |
def combine_sequences(a: List[int], b: List[int]) -> List[int]: | |
b_values_prime_number_count = get_prime_number_of_occurances_of_values_in_collection(b) | |
result_collection = [] | |
for element in a: | |
has_prime_number_count_int_b = b_values_prime_number_count.get(element, False) | |
if not has_prime_number_count_int_b: | |
result_collection.append(element) | |
return result_collection | |
# tests assert | |
# initial tests | |
assert combine_sequences([1, 2], [1, 1, 1, 1, 2, 2]) == [1] | |
assert combine_sequences([-1, 2], [-1, -1, -1, -1, 2, 2]) == [-1] | |
# swmansion exaple: | |
A = [2, 3, 9, 2, 5, 1, 3, 7, 10] | |
B = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10] | |
C = [2, 9, 2, 5, 7, 10] | |
assert combine_sequences(A, B) == C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment