Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

random.sample() does not properly check 'counts' parameter for negative entries, resulting in a flawed binary search. #134816

Copy link
Copy link
Closed
@boniest

Description

@boniest
Issue body actions

Bug report

Bug description:

the sample method in Random takes a counts parameter which is accumulated in the algorithm to cum_counts.

the total of counts (ie. the final element of cum_counts) is checked for non-negativity, but the individual elements of counts are not.

this causes a bug because the accumulated cum_counts is NOT strictly non-decreasing BUT a bisect (ie. binary search) is performed on cum_counts.

this call to Random.sample() always results in [3, 3] because a bisect using either 0 and 1 over cum_counts results in 3.

import random
result = random.sample([0,1,2,3,4], counts=[4,-6,-1,6,-1], k=2)
print(result) # always [3, 3]

CPython versions tested on:

3.13

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.