有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
def test1():
count = 1
for i in range(1,5) :
for j in range(1,5):
for k in range(1,5):
if i!=j and i !=k and j!=k:
count +=1
print(i,j,k)
print('总共有%d'%(count))
企业发放的奖金根据利润提成。利润(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,求应发放奖金总数?
程序分析:请利用数轴来分界,定位。
def test2():
arr = [1000000,600000,400000,200000,100000]
rat = [0.01,0.015,0.03,0.05,0.075,0.1]
I = int(input('输入当月利润I:'))
for i in range(0,6):
if(I > arr[i]):
sum = (I-arr[i])*rat[i]
print(sum)
break
一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
def test3():
# 通过数学的方法推导出
'''
x + 100 = n^2
x + 268 = m^2
得出 i*j = 168 (m+n = i, m-n = j )(i,j 至少有一个是偶数)
m = (i+j)/2, n = (i-j)/2
得出 i,j 都是偶数
'''
for i in range(1,85):
j = 168/i
if i>j and (i+j)%2 ==0 and (i-j)%2 ==0:
m,n = (i+j)/2,(i-j)/2
x = n*n-100
print('这个整数可能是:%d'%x)
题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:
def test4():
year = int(raw_input('year:'))
month = int(raw_input('month:'))
day = int(raw_input('day:'))
sum = 0 # 最后返回的天数
# 记录天数
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <=12:
sum += months[month-1]
else:
print("data is error")
sum += day
leap = 0
if year%400==0 or ((year % 4 ==0) and (year %100 !=0)):
leap = 1 # 闰年需要加1
if leap == 1 and month>2:
sum += 1
print('%d/%d/%d是%d的第%d天'%(year,month,day,year,sum))
输入三个整数x,y,z,请把这三个数由小到大输出
def test5():
x = int(input('输入x的值:'))
y = int(input('输入y的值:'))
z = int(input('输入z的值:'))
if x < y:
x,y = y,x
if x < z:
x,z=z,x
if(y < z):
y,z=z,y
print('x,y,z的值从小到大为',z,y,x)
def test5():
list = []
for i in range(3):
num = int(input('Inter:'))
list.append(num)
list.sort()
print(list)
题目:将一个列表的数据复制到另一个列表中。
程序分析:使用列表[:]
def test7():
a = [1,2,3]
b = a[:]
print(b)
题目:输出 9*9 乘法口诀表。
程序分析:分行与列考虑,共9行9列,i控制行,j控制列
def test8():
for i in range(1,10) :
print()
for j in range(1,i+1):
print("%d*%d=%d "%(i,j,i*j),end='')
题目:暂停一秒输出。
程序分析:使用 time 模块的 sleep() 函数
import time
def test9():
myD = {
1:'a',2:'b',3:'c'}
for key,value in dict.items(myD):
print(key,value)
time.sleep(1)
题目:暂停一秒输出,并格式化当前时间
def test10():
while(True):
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
time.sleep(1)
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位
def test13():
for n in range(100,1000):
i = n//100 # 在 Python3 中 取余符号是 //
j = n%100//10
k = n%100%10
if i**3 + j **3 + k**3 == n:
print(n)
题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5
程序分析:对n进行分解质因数,应先找到一个最小的质数index,然后按下述步骤完成:
def test14(n):
print('{} = '.format(n), end=" ")
if not isinstance(n, int) or n <= 0:
print('请输入一个正确的数字 !')
exit(0)
elif n in [1]:
print('{}'.format(n))
while n not in [1]: # 循环保证
for index in range(2,n+1):
if n % index ==0:
n //=index
if n == 1:
print(index)
else: # 如果 !=1 则 index 一定是素数
print('{}*'.format(index),end='')
break
题目:输出指定格式的日期。
程序分析:使用 datetime 模块
import datetime
def test16():
# 输出今日日期,格式为 dd/mm/yyyy。更多选项可以查看 strftime() 方法
print(datetime.date.today().strftime('%d/%m/%Y')) # 19/12/2020
# 创建日期对象
miyazakiBirthDate = datetime.date(2020, 12, 19)
print(miyazakiBirthDate.strftime('%d/%m/%Y')) # 19/12/2020
# 日期算术运算
miyazakiBirthNextDay = miyazakiBirthDate + datetime.timedelta(days=1)
print(miyazakiBirthNextDay.strftime('%d/%m/%Y')) # 20/12/2020
# 日期替换
miyazakiFirstBirthday = miyazakiBirthDate.replace(year=miyazakiBirthDate.year + 1)
print(miyazakiFirstBirthday.strftime('%d/%m/%Y')) # 19/12/2021
题目:求s=a+aa+aaa+aaaa+aa…a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。
程序分析:关键是计算出每一项的值
def test18(a,n):
s = 0
list = []
for i in range(n) :
s = s + a
a = a * 10
list.append(s)
print(list)
# reduce 计算列表和 reduce(add,list) add 为一个函数表达式,list 是要计算的列表
list = reduce(lambda x,y:x+y,list)
print(list)
题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数
def test19():
def isSum(n):
list = [1]
for i in range(2,n//2+1):
if n % i == 0 and i not in list:
list.append(i)
list.append(n//i)
return sum(list)
def isWanNum(n):
return isSum(n) == n
for n in range(2, 1001):
if isWanNum(n) :
print(n)
题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
def test20():
s,height = 0,100.0
for i in range(10):
s = s + height
height /=2
s = s + height
s -= height
print('共经过%f米,第10次的反弹有%f米高'% (s,height))
题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
程序分析:采取逆向思维的方法,从后往前推断。
def test21():
peach = 1 # 这是倒数第一天
for i in range(2,11): # 从倒数第二天到第一天
peach +=1
peach *=2
print(peach)
题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单
def test22():
list = ['x','y','z']
for a in list:
for b in list:
if a == b:
continue
for c in list:
if a==c or b==c:
continue
if a!='x' and c!='x' and c!='z':
print('联手名单为: a--%c\tb--%c\tc--%c' %(a,b,c))
题目:打印出如下图案(菱形)
*
***
*****
*******
*****
***
*
def test23():
# 前四行
for i in range(4):
for j in range(3-i):
print(' ',end='')
for k in range(2*i+1):
print('*',end='')
print() # 换一行
# 后三行
for i in range(3):
for j in range(1+i):
print(' ',end='')
for k in range(5-2*i):
print('*',end='')
print()
题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来
def test27():
def output(s,l):
if l == 0:
return
print(s[l-1],end='')
output(s,l-1)
s = raw_input('请输入字符:')
l = len(s)
output(s,l)
题目:按相反的顺序输出列表的值
def test32():
list = ['one','two','three']
print(list[::-1])
题目:按逗号分隔列表
def test33():
L = [1,2,3,4,5,6]
s1 = ','.join(str(s) for s in L)
print(s1)
题目:文本颜色设置
def test35():
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
print(bcolors.WARNING + "警告的颜色字体?" + bcolors.ENDC)
题目:模仿静态变量的用法
class Static:
StaticVar = 5
def varFunc(self):
self.StaticVar +=1
print(self.StaticVar)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print(Static.StaticVar)
a = Static()
for i in range(3):
a.varFunc()
题目:学习使用auto定义变量的用法。
程序分析:没有auto关键字,使用变量作用域来举例吧
def test42():
num = 2
def autofunc():
num = 1
print('internal block num = %d' % num)
num += 1
for i in range(3):
print('The num = %d' % num)
num += 1
autofunc()
题目:模仿静态变量(static)另一案例。
程序分析:演示一个python作用域使用方法
class Num:
nNum = 1
def inc(self):
self.nNum +=1
print('nNum= %d'% self.nNum)
def test43():
nNum = 2
inst = Num()
for i in range(3):
nNum +=1
print('The nNum= %d'% nNum)
inst.inc()
题目:使用 lambda 来创建匿名函数
def test49():
MAXIMUM = lambda x,y:(x>y)*x + (x<y)*y
MINIMUM = lambda x, y: (x > y) * y + (x < y) * x
a = 10
b = 20
print('比较小的数为 %d' %(MINIMUM(a,b)))
print('比较大的数为 %d' %(MAXIMUM(a,b)))
输出一个随机函数
生成 1~2 的随机数
import random
def test50():
for i in range(10):
print(random.uniform(1,2),end=' ')
题目:画图,学用circle画圆形
from tkinter import*
def test56():
canvas = Canvas(width=600, height=600, bg='yellow')
canvas.pack(expand=YES, fill=BOTH)
k = 1
j = 1
for i in range(0, 26): # 画 26 个圈圈
canvas.create_oval(310 - k, 250 - k, 310 + k, 250 + k, width=1)
k += j
j += 0.5
mainloop()
题目:画图,学用line画直线
画一个坐标系,在画一条 y = x 的直线
from tkinter import*
def test57():
canvas = Canvas(width=600, height=600, bg='black')
canvas.pack(expand=YES, fill=BOTH)
# y轴
x0 = 200
y0 = 100
x1 = 200
y1 = 600
canvas.create_line(x0, y0, x1, y1, width=1, fill='white')
# x 轴
x0 = 50
x1 = 600
y0 = y1 = 350
canvas.create_line(x0, y0, x1, y1, width=1, fill='white')
# y = x 的直线
x0,y0 = 200,350
x1,y1 = 200,350
for i in range(20):
canvas.create_line(x0,y0,x1,y1,width=1,fill='red')
x0 = x0 + 10
y0 = y0 - 10
x1 = x1 - 10
y1 = y1 + 10
mainloop()
题目:画图,学用rectangle画方形
def test58():
root = Tk()
root.title("Canvas")
canvas = Canvas(root,width=400,height=400,bg='yellow')
x0 = y0 = 263
x1 = y1 = 273
for i in range(19):
canvas.create_rectangle(x0,y0,x1,y1)
x0 -=5
y0 -=5
x1 +=5
y1 +=5
canvas.pack()
root.mainloop()
题目:画图,综合例子。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位
import math
def test59() :
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 150
y0 = 100
canvas.create_oval(x0 - 10, y0 - 10, x0 + 10, y0 + 10)
canvas.create_oval(x0 - 20, y0 - 20, x0 + 20, y0 + 20)
canvas.create_oval(x0 - 50, y0 - 50, x0 + 50, y0 + 50)
B = 0.809
for i in range(16):
a = 2 * math.pi / 16 * i
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 * math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
canvas.create_oval(x0 - 60, y0 - 60, x0 + 60, y0 + 60)
for k in range(501):
for i in range(17):
a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 + math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
for j in range(51):
a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k - 1
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 * math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
mainloop()
打印杨辉三角
'''打印出杨辉三角'''
def test61():
a = []
# 初始化空格
for i in range(10):
a.append([])
for j in range(10):
a[i].append(0)
# 初始化特殊位置为 1
for i in range(10):
a[i][0] = a[i][i] = 1
# 计算
for i in range(2,10):
for j in range(1,i):
a[i][j] = a[i-1][j-1] + a[i-1][j]
from sys import stdout
for i in range(10):
for j in range(i+1):
stdout.write(str(a[i][j]))
stdout.write(' ')
print()
查找字符串
def test62():
s1 = 'abc'
s2 = 'defabc'
index = s2.find(s1) # 返回开始的下标
print(index)
题目:画椭圆
from tkinter import *
def test63():
x = 360
y = 160
top = y - 30
bottom = y - 30
canvas = Canvas(width=400, height=600, bg='white')
for i in range(20):
canvas.create_oval(250 - top, 250 - bottom, 250 + top, 250 + bottom)
top -= 5
bottom += 5
canvas.pack()
mainloop()
题目:利用 ellipse 和 rectangle 画图
def test64():
canvas = Canvas(width=400, height=600, bg='white')
left = 20
right = 50
top = 50
num = 15
for i in range(num):
canvas.create_oval(250 - right, 250 - left, 250 + right, 250 + left)
canvas.create_oval(250 - 20, 250 - top, 250 + 20, 250 + top)
canvas.create_rectangle(20 - 2 * i, 20 - 2 * i, 10 * (i + 2), 10 * (i + 2))
right += 5
left += 5
top += 10
canvas.pack()
mainloop()
题目:一个最优美的图案。
import math
class PTS:
def __init__(self):
self.x = 0
self.y = 0
points = []
def LineToDemo():
screenx = 400
screeny = 400
canvas = Canvas(width = screenx,height = screeny,bg = 'white')
AspectRatio = 0.85
MAXPTS = 15
h = screeny
w = screenx
xcenter = w / 2
ycenter = h / 2
radius = (h - 30) / (AspectRatio * 2) - 20
step = 360 / MAXPTS
angle = 0.0
for i in range(MAXPTS):
rads = angle * math.pi / 180.0
p = PTS()
p.x = xcenter + int(math.cos(rads) * radius)
p.y = ycenter - int(math.sin(rads) * radius * AspectRatio)
angle += step
points.append(p)
canvas.create_oval(xcenter - radius,ycenter - radius,
xcenter + radius,ycenter + radius)
for i in range(MAXPTS):
for j in range(i,MAXPTS):
canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y)
canvas.pack()
mainloop()
题目:找到年龄最大的人,并输出。请找出程序中有什么问题。
def test78():
person = {
"li": 18, "wang": 50, "zhang": 20, "sun": 22}
m = 'li'
for key in person.keys():
if person[m] < person[key]:
m = key
print('%s,%d' % (m, person[m]))
八进制转十进制
def test78():
person = {
"li": 18, "wang": 50, "zhang": 20, "sun": 22}
m = 'li'
for key in person.keys():
if person[m] < person[key]:
m = key
print('%s,%d' % (m, person[m]))
题目:字符串日期转换为易读的日期格式。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")
print dt
题目:从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止。
if __name__ == '__main__':
from sys import stdout
filename = raw_input('输入文件名:\n')
fp = open(filename,"w")
ch = raw_input('输入字符串:\n')
while ch != '#':
fp.write(ch)
stdout.write(ch)
ch = raw_input('')
fp.close()
题目:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中。
if __name__ == '__main__':
import string
fp = open('test1.txt')
a = fp.read()
fp.close()
fp = open('test2.txt')
b = fp.read()
fp.close()
fp = open('test3.txt','w')
l = list(a + b)
l.sort()
s = ''
s = s.join(l)
fp.write(s)
fp.close()
题目:列表转换为字典。
i = ['a', 'b']
l = [1, 2]
print dict([i,l])