Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

python - Top 80% Percent of Sales

My goal is to filter only the top 80% of products that makeup of sales

I have a Total of 100 products and the total of sales was 15000, so to find out what is the percent of the product of sales I'm doing this

product_dict = {}
for product in products:
    percent_from_sale = product.quantity / total_quantity * 100
    product_dict[product] = percent_from_sale

so after this I have dict with the key product and values is the percent of this product sale, but how can I filter only top 80%?

question from:https://stackoverflow.com/questions/65951771/top-80-percent-of-sales

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can define generator function which will yield elements until cumulative sum reach some limit:

def iter_until(src, limit, key):
    cumulative_sum = 0
    for element in src:
        yield element
        cumulative_sum += key(element)
        if cumulative_sum >= limit:
            break

Let's generate input similar to your:

from collections import namedtuple
from random import shuffle

product = namedtuple("product", "name quantity")
total_quantity = 15000
products = [product(f"product{i}", total_quantity // (2 ** i)) for i in range(1, 101)]
shuffle(products)

Now you can iterate over generator function. You can create list of top 80% of sales:

sorted_products = sorted(products, key=lambda x: x.quantity, reverse=True)
top_80_percent = list(iter_until(sorted_products, total_quantity * 0.8, lambda x: x.quantity))

You can create dict (what you're trying to do in code form question):

sorted_products = sorted(products, key=lambda x: x.quantity, reverse=True)
top_80_percent = {p.name: p.quantity for p in iter_until(sorted_products, total_quantity * 0.8, lambda x: x.quantity)}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...