实例001:数字组合
题目:有四个数字: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)
调用全排列函数permutations:
nums表示需要排列的元素集合,3表示长度,此例为A43(排列组合)432
import itertools
total = 0
nums = list(range(1, 4 + 1))
for num in itertools.permutations(nums, 3):
'''
print(num)
'''
print(num[0], num[1], num[2])
total += 1
print(total)
- 以上也可以知道permutations索引顺序和我们自己的循环顺序是一致的
=================================2022.03.25
实例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,求应发放奖金总数?
profit = int(input('show me the money '))
bonus = 0
thresholds = [100000, 200000, 400000, 600000, 1000000]
rate = [0.1, 0.075, 0.05, 0.03, 0.015, 0.01]
for i in range(len(thresholds)) :
if profit <= thresholds[i] :
bonus += profit * rate[i]
profit = 0
break
else :
bonus += thresholds[i] * rate[i]
profit -= thresholds[i]
profit = profit * rate[-1]
print(bonus)
for if 都有冒号
=====================================2022.03.26
实例003:完全平方数 题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
n = 0
while (n + 1)**2 - n ** 2 <= 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)
当(n+1)2 - n2 等于168时,以后的(n+1)2和n2的差肯定大于168,以此为上界条件搜索n+1的取值范围;再判断完全平方数(取根号小数位为0)。
=====================================2022.03.27
实例004:这天第几天 题目: 输入某年某月某日,判断这一天是这一年的第几天?
def isleapyear(y):
print (y % 400 == 0 or (y % 4 == 0 and y % 100 !=0))
dofm = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 31, 31]
res = 0
year = int(input('year : '))
month = int(input('month : '))
day = int(int(input('day : ')))
if(isleapyear(year)):
dofm[2] += 1
for i in range(month):
res += dofm[i]
print(res + day)
定义函数def:;range范围左闭右开;
==========================================2022.03.28
实例005:三数排序 题目: 输入三个整数x,y,z,请把这三个数由小到大输出。
raw = []
for i in range(3) :
x = int(input('please input %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)
append是list的方法,将元素放置最后,也可以放置list;
值交换:a, b = b, a