Reputation: 23098
I want to choose 15 images from many collections. Number of images depends on the proportion of images from that collection.
My code is as:
image_counts = [16, 2, 14]
total_images = 0
for i in image_counts:
total_images += i
proportions = [1.0 * i / total_images for i in image_counts]
counts = [int( round( 15 * i)) for i in proportions]
But the output [8, 1, 7]
adds up to 16, due to rounding. How to get a list that adds up to exactly 15?
Upvotes: 0
Views: 97
Reputation: 3695
One of your options is this:
image_counts = [16, 2, 14]
total_images = sum(image_counts)
proportions = [1.0 * i / total_images for i in image_counts]
counts = [int(15 * i) for i in proportions]
if sum(counts) < 15:
counts[counts.index(min(counts))] += 1
To complete this answer:
counts[counts.index(min(counts))] += 15 - sum(counts[1:]) # from user1654936
and truncating the final list to 15 elements.
Upvotes: 1
Reputation: 653
In most cases it is not possible to choose the counts exactly according to the calculated proportions. So, because you have to deviate from the proportions anyway, you could just alter e.g. the first number of your counts
list so that it adds up to the required total number:
image_counts = [16, 2, 14]
total_images = sum(image_counts)
proportions = [1.0 * i / total_images for i in image_counts]
counts = [int( round( 15 * i)) for i in proportions]
counts[0] = 15 - sum(counts[1:])
Upvotes: 1
Reputation: 27097
You can't in general have the total be 15 (or whatever you want) and the correct proportions unless some very specific conditions are satisfied by the number of images in each collection and the number that you want.
So you need to decide how to adjust those numbers to get something close to what you want. Do you want the proportions to be nearly correct (and even now it's only "nearly", since you're already rounding)? Or do you want to allow a number other than 15 in total?
also:
total_images = sum(image_counts)
Upvotes: 0