How to select N unique random values that appear exactly once in an existing list with Python

1 Answer

0 votes
from collections import Counter
import random

"""
    Goal:
    - Select N random values that appear exactly once in the list.
    - The list includes duplicates, but only values with frequency = 1
      are eligible for selection.

    Approach:
    1. Count frequencies using collections.Counter.
    2. Collect values that appear exactly once.
    3. Randomly sample N values using random.sample.
    4. Return them and print them.

    Notes:
    - Uses Python's built-in tools for clarity and efficiency.
    - Uses structured, expressive functions.
"""

#---------------------------------------------------------------
# Build a frequency map: value -> count
#---------------------------------------------------------------
def build_frequency_map(data):
    # Counter returns a dictionary-like object: value -> count
    return Counter(data)

#---------------------------------------------------------------
# Collect values that appear exactly once
#---------------------------------------------------------------
def collect_globally_unique_values(data, freq):
    unique = []

    for value in data:
        if freq[value] == 1:
            unique.append(value)

    return unique

#---------------------------------------------------------------
# Randomly select N values from the unique list
#---------------------------------------------------------------
def select_random_unique(unique, N):
    # Clamp N to available unique values
    if N > len(unique):
        N = len(unique)

    # random.sample selects N distinct elements without replacement
    return random.sample(unique, N)

#---------------------------------------------------------------
# Print helper
#---------------------------------------------------------------
def print_list(lst):
    print(" ".join(str(v) for v in lst))

#---------------------------------------------------------------
# Main program
#---------------------------------------------------------------
if __name__ == "__main__":

    # Example list with duplicates
    data = [
        5, 12, 5, 19, 5, 33, 19, 5, 8, 8, 8, 59, 61, 17, 3, 5, 3, 74, 83, 90, 3, 1
    ]

    # Step 1: Build frequency map
    freq = build_frequency_map(data)

    # Step 2: Collect values that appear exactly once
    unique_values = collect_globally_unique_values(data, freq)

    # Step 3: Choose how many unique random values to select
    N = 5

    # Step 4: Select N random unique values
    random_selection = select_random_unique(unique_values, N)

    # Step 5: Print results
    print("Values that appear exactly once:")
    print_list(unique_values)

    print("\nRandom selection ({} values):".format(N))
    print_list(random_selection)



"""
run:

Values that appear exactly once:
12 33 59 61 17 74 83 90 1

Random selection (5 values):
12 59 1 90 17

"""

 



answered Sep 13 by avibootz

Related questions

...