Python 案例002(获取不同数据区间的和)

题目内容来自网络 ,加入了个人理解的过程 ,和点评


#! /usr/bin/python
# -*- coding:utf-8 -*-

"""
request :
题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;
利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;
20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;
60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,
从键盘输入当月利润I,求应发放奖金总数?
"""

#define two lists
# method 1
revenue=[1000000,600000,400000,200000,100000,0]
deduct=[0.01,0.015,0.03,0.05,0.075,0.1]
profit = int(raw_input("please enter the revenue:"))
earning = 0
for x  in range(len(deduct)):
    if profit > revenue[x]:
        earning+=(profit-revenue[x])*deduct[x]
        profit=revenue[x]
print earning

#method 2  ,求出每个区间的数据
nprofit = int(raw_input("please enter the revenue:"))
nrevenue=[1000000,600000,400000,200000,100000,0]
ndeduct=[0.01,0.015,0.03,0.05,0.075,0.1]
# define an new list to put this data  in
nearning = 0
newprofit =[]
for x in range(len(nrevenue)):
    if nprofit > nrevenue[x]:
        nearning = (nprofit - nrevenue[x])   # 计算每个区间段的数据值
        nprofit = nrevenue[x]
        newprofit.append(nearning)
    else:
        newprofit.append(0)  # 用 zero 填充默认值 ,相乘后不影响结果
# try to using lambda
zipdata = zip(newprofit,ndeduct)
print zipdata
trynew = sum(map(lambda (x,y):x*y,zipdata))   # x, y  是一个zipdata 中的元组 tuple
print trynew                                  # 这个地方很容易跟spark 中的map  reduce 混淆


#method 3, 考虑用列表推到  ??

# result :
"""
please enter the revenue:100000000
1029500.0
please enter the revenue:100000000
[(99000000, 0.01), (400000, 0.015), (200000, 0.03), (200000, 0.05), (100000, 0.075), (100000, 0.1)]
1029500.0
"""







原文地址:https://www.cnblogs.com/TendToBigData/p/10501230.html