python每日一题

2020-04-11  本文已影响0人  DarknessShadow

实例001:"数字组合"

题目有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?

nums = [1, 2, 3, 4]
nums = list(map(str, nums))
temp = []
st1, st2, st3 = '', '', ''

def getNums(nums, i):
    tmp = []
    for num in nums:
        if i == num:
            continue
        tmp.append(num)
    return tmp

for i in nums:
    st1 = i
    temp_st1 = getNums(nums, i)
    for j in temp_st1:
        st2 = j
        for h in getNums(temp_st1, j):
            st3 = h
            s = st1 + st2 + st3
            temp.append(s)

print(len(temp))
print(temp)

简便方法

import itertools
num = [1, 2, 3, 4]
selects = []
for i in itertools.permutations(num, 3):
    selects.append(i)

print(selects)
print(len(selects))
# permutations类提供的简便方法它会直接将数组中的元素按照后面给定数字获得指定数目的元素不重复的所有组合的列表

实例002:"个税计算"

题目 企业发放的奖金根据利润提成。利润(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,求应发放奖金总数?

程序分析 分区间计算即可。

# 枫
# 每日一题 002 "个税计算"
class NegativeNumberException(Exception):
    def __init__(self):
        pass

    def __str__(self):
        print("亲,输入的利润不能为负数哦~")

def getaward():
    while True:
        try:
            profile = input('亲,请输入当月企业利润(单位:万元):')
            if not profile.isdigit():
                raise ValueError
            elif decimal.Decimal(profile) < 0:
                raise NegativeNumberException
            return calculate(decimal.Decimal(profile))
        except ValueError:
            print('亲,您输入的企业利润是非法字符,请输入正确的企业利润~')
        except NegativeNumberException:
            print('亲,您输入的企业利润是非法字符,请输入正确的企业利润~')

def calculate(profile):
    with decimal.localcontext() as ext:
        ext.prec = 4
        if profile <= 10:
            return profile * decimal.Decimal(0.1)
        elif profile <= 20:
            return calculate(10) + (profile - 10) * decimal.Decimal(0.075)
        elif profile <= 40:
            return calculate(20) + (profile - 20) * decimal.Decimal(0.05)
        elif profile <= 60:
            return calculate(40) + (profile - 40) * decimal.Decimal(0.03)
        elif profile <= 100:
            return calculate(60) + (profile - 60) * decimal.Decimal(0.015)
        else:
            return calculate(100) + (profile - 100) * decimal.Decimal(0.01)


if __name__ == '__main__':
    print('亲亲,你所以获得的提成为:%s万元,很棒有呦,继续加油~' % str(getaward()))
上一篇 下一篇

猜你喜欢

热点阅读