Fix BitArray.from_counts
/from_samples
to not fail for input with only 0
outcome and num_bits=None
(backport #12800)
#12820
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Partial fix for #12765.
That issue points out two problems with
BitArray.from_counts
/BitArray.from_samples
. The more severe problem is that these methods fail with an error if the input (e.g. a counts dictionary) contains only the0
outcome, andnum_bits
is left at the default value ofNone
.The methods try to infer
num_bits
as the number of bits needed to represent the largest outcome (e.g. bitstring) contained in the input data. If the largest outcome is0
when converted to an integer (e.g. the bitstring"0"
), the number of bits inferred is0
, which can be surprising, and also leads to an error.This small PR interprets
0
as represented by 1 bit instead of by 0 bits, the suggested correct behavior in #12765.The less severe problem, not fixed here, is that currently any information about
num_bits
present in the input bitstring lengths gets ignored. That problem seemed less trivial to me. I put some thoughts here.This is an automatic backport of pull request #12800 done by [Mergify](https://mergify.com).