本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
以下文章來源于python資料分析之禪 ,作者鳥哥
前言
雙十一還有不到10天,購物車已經快加滿了,但是錢包里就這么多錢,如何用現有的錢買到更多喜歡的東西,成為我比較頭疼的事,因為我已經被各種組合加法搞暈了
于是我決定用python做個雙十一購物攻略,把復雜的計算程序交給電腦解決,自動列出能購買哪些商品,成果如下:
下面給大家詳細介紹一下實作程序:
首先將要購買的商品及價格放入表格中:
用pandas讀取表格,并將商品名稱和價格組合成字典:
import pandas as pd
data=https://www.cnblogs.com/hhh188764/archive/2020/11/03/pd.read_excel('商品.xlsx')
goods_price={}
for i,j in zip(list(data['名稱']),list(data['原價'])):
goods_price[i]=j
goods_price
{'訓練短袖': 259,
'訓練外套': 589,
'運動鞋': 389,
'跑步鞋': 788,
'衛衣': 209,
'臺燈': 119,
'書籍': 246}
計算商品總價和折扣情況并輸出
all_price=sum([int(goods_price[good]) for good in list(goods_price.keys())]) #求商品總價格
all_discount=int(all_price/300)
print('全部商品原價總額為{}元'.format(all_price))
print('全部商品可以滿減{0}次'.format(all_discount))
print('滿減后商品價格總額為{}元'.format(all_price-40*all_discount)) #每滿300減40
全部商品原價總額為2599元
全部商品可以滿減8次
滿減后商品價格總額為2279元
輸入購買力
money_max=int(input('請輸入購買最大金額:'))
money_min=int(input('請輸入購買最小金額:'))
對所有商品進行組合
import itertools
goods1=list(goods_price.keys())
goods2 = []
for i in range(1,len(goods1)+1):
iter = itertools.combinations(goods1,i)
goods2.append(list(iter))
以商品組合為鍵,價格為值,創建字典
results={}
for i in goods2:
for j in i:
sum_price = 0
sum_price+=sum([int(goods_price[k]) for k in j])
results[j]=sum_price
輸出滿足條件的滿減商品
for i in list(results.keys()):
last_price=results[i]-int(results[i]/300)*40
if last_price>money_min and last_price<money_max:
print('{0:{3}^20}\t{1:{3}^10}\t{2:^10}'.format(' '.join(i), '原價為{}元'.format(results[i]),
'滿減后價格為{}元'.format(last_price),chr(12288)))
最終的成果如下圖:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/201085.html
標籤:其他
