Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8730437
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T09:01:14+00:00 2026-06-13T09:01:14+00:00

I’m looking for a reasonable definition of a function weighted_sample that does not return

  • 0

I’m looking for a reasonable definition of a function weighted_sample that does not return just one random index for a list of given weights (which would be something like

def weighted_choice(weights, random=random):
    """ Given a list of weights [w_0, w_1, ..., w_n-1],
        return an index i in range(n) with probability proportional to w_i. """
    rnd = random.random() * sum(weights)
    for i, w in enumerate(weights):
        if w<0:
            raise ValueError("Negative weight encountered.")
        rnd -= w
        if rnd < 0:
            return i
    raise ValueError("Sum of weights is not positive")

to give a categorical distribution with constant weights) but a random sample of k of those, without replacement, just as random.sample behaves compared to random.choice.

Just as weighted_choice can be written as

lambda weights: random.choice([val for val, cnt in enumerate(weights)
    for i in range(cnt)])

weighted_sample could be written as

lambda weights, k: random.sample([val for val, cnt in enumerate(weights)
    for i in range(cnt)], k)

but I would like a solution that does not require me to unravel the weights into a (possibly huge) list.

Edit: If there are any nice algorithms that give me back a histogram/list of frequencies (in the same format as the argument weights) instead of a sequence of indices, that would also be very useful.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T09:01:15+00:00Added an answer on June 13, 2026 at 9:01 am

    From your code: ..

    weight_sample_indexes = lambda weights, k: random.sample([val 
            for val, cnt in enumerate(weights) for i in range(cnt)], k)
    

    .. I assume that weights are positive integers and by “without replacement” you mean without replacement for the unraveled sequence.

    Here’s a solution based on random.sample and O(log n) __getitem__:

    import bisect
    import random
    from collections import Counter, Sequence
    
    def weighted_sample(population, weights, k):
        return random.sample(WeightedPopulation(population, weights), k)
    
    class WeightedPopulation(Sequence):
        def __init__(self, population, weights):
            assert len(population) == len(weights) > 0
            self.population = population
            self.cumweights = []
            cumsum = 0 # compute cumulative weight
            for w in weights:
                cumsum += w   
                self.cumweights.append(cumsum)  
        def __len__(self):
            return self.cumweights[-1]
        def __getitem__(self, i):
            if not 0 <= i < len(self):
                raise IndexError(i)
            return self.population[bisect.bisect(self.cumweights, i)]
    

    Example

    total = Counter()
    for _ in range(1000):
        sample = weighted_sample("abc", [1,10,2], 5)
        total.update(sample)
    print(sample)
    print("Frequences %s" % (dict(Counter(sample)),))
    
    # Check that values are sane
    print("Total " + ', '.join("%s: %.0f" % (val, count * 1.0 / min(total.values()))
                               for val, count in total.most_common()))
    

    Output

    ['b', 'b', 'b', 'c', 'c']
    Frequences {'c': 2, 'b': 3}
    Total b: 10, c: 2, a: 1
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need a function that will clean a strings' special characters. I do NOT
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have a small JavaScript validation script that validates inputs based on Regex. I
I've got a string that has curly quotes in it. I'd like to replace
I am reading a book about Javascript and jQuery and using one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.