python实战训练---基础训练(1)

数字组合

题目:
有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
程序分析 :遍历全部可能,把有重复的剃掉。

total=0
for i in range(1,5):
    for j in range(1,5):
        for k in range(1,5):
            if ((i!=j)and(j!=k)and(k!=i)):
                print(i,j,k)
                total+=1
print(total)

实力输出结果:

1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
24

简便方法 用itertools中的permutations即可。

import itertools
sum2=0
a=[1,2,3,4]
for i in itertools.permutations(a,3):
    print(i)
    sum2+=1
print(sum2)

实例输出结果:

(1, 2, 3)
(1, 2, 4)
(1, 3, 2)
(1, 3, 4)
(1, 4, 2)
(1, 4, 3)
(2, 1, 3)
(2, 1, 4)
(2, 3, 1)
(2, 3, 4)
(2, 4, 1)
(2, 4, 3)
(3, 1, 2)
(3, 1, 4)
(3, 2, 1)
(3, 2, 4)
(3, 4, 1)
(3, 4, 2)
(4, 1, 2)
(4, 1, 3)
(4, 2, 1)
(4, 2, 3)
(4, 3, 1)
(4, 3, 2)
24

个税计算

题目 :
企业发放的奖金根据利润提成。

  • 利润(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,求应发放奖金总数?

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

profit=int(input('Show me the money: '))
bonus=0
thresholds=[100000,100000,200000,200000,400000]
rates=[0.1,0.075,0.05,0.03,0.015,0.01]
for i in range(len(thresholds)):
    if profit<=thresholds[i]:
        bonus+=profit*rates[i]
        profit=0
        break
    else:
        bonus+=thresholds[i]*rates[i]
        profit-=thresholds[i]
bonus+=profit*rates[-1]
print('最终应得奖金',bonus)

实例输出结果:

Show me the money: 900000
最终应得奖金 38000.0

完全平方数

题目:
一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?

程序分析:
因为168对于指数爆炸来说实在太小了,所以可以直接省略数学分析,用最朴素的方法来获取上限:

n=0
while (n+1)**2-n*n<=168:
    n+=1

print(n+1)

实例结果:

85

思路是:最坏的结果是n的平方与(n+1)的平方刚好差168,由于是平方的关系,不可能存在比这更大的间隙。
至于判断是否是完全平方数,最简单的方法是:平方根的值小数为0即可。
结合起来:

n=0
while (n+1)**2-n*n<=168:
    n+=1

for i in range((n+1)**2):
    if i**0.5==int(i**0.5) and (i+168)**0.5==int((i+168)**0.5):
        print(i-100)

实例结果:

-99
21
261
1581

这天第几天

题目: 输入某年某月某日,判断这一天是这一年的第几天?

程序分析: 特殊情况,闰年时需考虑二月多加一天:

def isLeapYear(y):
    return (y%400==0 or (y%4==0 and y%100!=0))
DofM=[0,31,28,31,30,31,30,31,31,30,31,30]
res=0
year=int(input('Year:'))
month=int(input('Month:'))
day=int(input('day:'))
if isLeapYear(year):
    DofM[2]+=1
for i in range(month):
    res+=DofM[i]
print(res+day)

实例运行结果:

Year:2020
Month:7
day:21
203

三数排序

题目:
输入三个整数x,y,z,请把这三个数由小到大输出。

程序分析: 练练手就随便找个排序算法实现一下,偷懒就直接调函数。

raw=[]
for i in range(3):
    x=int(input('int%d: '%(i)))
    raw.append(x)
    
for i in range(len(raw)):
    for j in range(i,len(raw)):
        if raw[i]>raw[j]:
            raw[i],raw[j]=raw[j],raw[i]
print(raw)

实例结果:

int0: 1
int1: 5
int2: 3
[1, 3, 5]

第二种:

raw2=[]
for i in range(3):
    x=int(input('int%d: '%(i)))
    raw2.append(x)
print(sorted(raw2))

实例结果:

int0: 1
int1: 5
int2: 3
[1, 3, 5]

猜你喜欢

转载自blog.csdn.net/xdc1812547560/article/details/107560256