Python 经典例题
1 循环
题目:一个数如果恰好等于它的因子之和,这个数就称为”完数”。例如6=1+2+3.编程找出1000以内的所有完数。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from sys import stdout
for j in range(2,1001):
k = []
n = -1
s = j
for i in range(1,j):
if j % i == 0:
n += 1
s -= i
k.append(i)
if s == 0:
print j
for i in range(n):
stdout.write(str(k[i]))
stdout.write(' ')
print k[n]
2
猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x2 = 1
for day in range(9,0,-1):
x1 = (x2 + 1) * 2
x2 = x1
print x1
range(self, begin, stop, step)
一个简单的数学问题。
3
题目:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = int(raw_input("请输入一个数字:\n"))
x = str(a)
flag = True
for i in range(len(x)/2):
if x[i] != x[-i - 1]:
flag = False
break
if flag:
print "%d 是一个回文数!" % a
else:
print "%d 不是一个回文数!" % a
可以用负数来表示从后往前数。
4
题目:按相反的顺序输出列表的值。
a = ['one', 'two', 'three']
for i in a[::-1]:
print (i)
a[::-1] #表示从-1开始遍历
5
题目:按逗号分隔列表。
L = [1,2,3,4,5]
s1 = ','.join(str(n) for n in L)
print (s1)
join #表示以什么为间隔点,产生新的字符串。
6
显示字体颜色。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
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
格式:\033[显示方式;前景色;背景色m
说明:
前景色 背景色 颜色
---------------------------------------
30 40 黑色
31 41 红色
32 42 绿色
33 43 黃色
34 44 蓝色
35 45 紫红色
36 46 青蓝色
37 47 白色
显示方式 意义
-------------------------
0 终端默认设置
1 高亮显示
4 使用下划线
5 闪烁
7 反白显示
8 不可见
例子:
\033[1;31;40m <!--1-高亮显示 31-前景色红色 40-背景色黑色-->
\033[0m <!--采用终端默认设置,即取消颜色设置-->
7
题目:将一个数组逆序输出。
程序分析:用第一个与最后一个交换。
if __name__ == '__main__':
a = [9,6,5,4,1]
N = len(a)
print a
for i in range(len(a) / 2):
a[i],a[N - i - 1] = a[N - i - 1],a[i]
print a
8
题目:模仿静态变量的用法。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def varfunc():
var = 0
print 'var = %d' % var
var += 1
if __name__ == '__main__':
for i in range(3):
varfunc()
# 类的属性
# 作为类的一个属性吧
class Static:
StaticVar = 5
def varfunc(self):
self.StaticVar += 1
print self.StaticVar
print Static.StaticVar
a = Static()
for i in range(3):
a.varfunc()
9
题目:学习使用auto定义变量的用法。
程序分析:没有auto关键字,使用变量作用域来举例吧。
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()
10
题目:模仿静态变量(static)另一案例。
程序分析:演示一个python作用域使用方法
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Num:
nNum = 1
def inc(self):
self.nNum += 1
print 'nNum = %d' % self.nNum
if __name__ == '__main__':
nNum = 2
inst = Num()
for i in range(3):
nNum += 1
print 'The num = %d' % nNum
inst.inc()
python中if name == ‘main‘: 的解析
当你打开一个.py文件时,经常会在代码的最下面看到if name == ‘main‘:,现在就来介 绍一下它的作用.
模块是对象,并且所有的模块都有一个内置属性 name。一个模块的 name 的值取决于您如何应用模块。如果 import 一个模块,那么模块name 的值通常为模块文件名,不带路径或者文件扩展名。但是您也可以像一个标准的程序样直接运行模块,在这 种情况下, name 的值将是一个特别缺省”main“。
在cmd 中直接运行.py文件,则name的值是’main‘;
而在import 一个.py文件后,name的值就不是’main‘了;
从而用if name == ‘main‘来判断是否是在直接运行该.py文件
如:
#Test.py
class Test:
def __init(self):pass
def f(self):print 'Hello, World!'
if __name__ == '__main__':
Test().f()
#End
你在cmd中输入:
C:>python Test.py
Hello, World!
说明:”name == ‘main‘”是成立的
你再在cmd中输入:
C:>python
import Test
Test.name #Test模块的name
‘Test’
name #当前程序的name
‘main’
无论怎样,Test.py中的”name == ‘main‘”都不会成立的!
所以,下一行代码永远不会运行到!
也就是说,
import test
class Num:
nNum = 1
def inc(self):
self.nNum += 1
print('nNum = %d' % self.nNum)
#test.__name__ = 'yan' 如果这句没有写,那就不会有任何输入。
if __name__ == 'yan':
nNum = 2
inst = Num()
for i in range(3):
nNum += 1
print ('The num = %d' % nNum)
inst.inc()
11
实现交换数字。
def exchange(a,b):
a,b = b,a
return (a,b)
if __name__ == '__main__':
x = 10
y = 20
print ('x = %d,y = %d' % (x,y))
x,y = exchange(x,y)
print ('x = %d,y = %d' % (x,y))
12
题目:使用lambda来创建匿名函数。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
MAXIMUM = lambda x,y : (x > y) * x + (x < y) * y
MINIMUM = lambda x,y : (x > y) * y + (x < y) * x
if __name__ == '__main__':
a = 10
b = 20
print 'The largar one is %d' % MAXIMUM(a,b)
print 'The lower one is %d' % MINIMUM(a,b)
Python匿名函数详解
13
题目:输出一个随机数。
程序分析:使用 random 模块。(如果要输出整数,就强制类型转换。)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import random
#生成 10 到 20 之间的随机数
print random.uniform(10, 20)
14
题目:画图,学用circle画圆形.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
from Tkinter import *
canvas = Canvas(width=800, height=600, bg='yellow')
canvas.pack(expand=YES, fill=BOTH)
k = 1
j = 1
for i in range(0,26):
canvas.create_oval(310 - k,250 - k,310 + k,250 + k, width=1)
k += j
j += 0.3
mainloop()
15
题目:画图,学用line画直线。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
from Tkinter import *
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
canvas.create_line(x0,y0,x0,y1, width=1, fill='red')
x0 = x0 - 5
y0 = y0 - 5
x1 = x1 + 5
y1 = y1 + 5
x0 = 263
y1 = 275
y0 = 263
for i in range(21):
canvas.create_line(x0,y0,x0,y1,fill = 'red')
x0 += 5
y0 += 5
y1 += 5
mainloop()
16
题目:画图,学用rectangle画方形。
程序分析:
rectangle(int left, int top, int right, int bottom)
参数说明:(left ,top )为矩形的左上坐标,(right,bottom)为矩形的右下坐标,两者可确定一个矩形的大小
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
from Tkinter import *
root = Tk()
root.title('Canvas')
canvas = Canvas(root,width = 400,height = 400,bg = 'yellow')
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
canvas.create_rectangle(x0,y0,x1,y1)
x0 -= 5
y0 -= 5
x1 += 5
y1 += 5
canvas.pack()
root.mainloop()
17
题目:打印出杨辉三角形(要求打印出10行如下图)。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
a = []
for i in range(10):
a.append([])
for j in range(10):
a[i].append(0)
for i in range(10):
a[i][0] = 1
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()
18 画椭圆
题目:画椭圆ellipse。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
from Tkinter import *
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()
19 画图
题目:利用ellipse 和 rectangle 画图。。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
from Tkinter import *
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()
20 画图
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
class PTS:
def __init__(self):
self.x = 0
self.y = 0
points = []
def LineToDemo():
from Tkinter import *
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()
if __name__ == '__main__':
LineToDemo()
21 递归
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
n = int(raw_input('the total number is:\n'))
m = int(raw_input('back m:\n'))
def move(array,n,m):
array_end = array[n - 1]
for i in range(n - 1,-1,- 1):
array[i] = array[i - 1]
array[0] = array_end
m -= 1
if m > 0:move(array,n,m)
number = []
for i in range(n):
number.append(int(raw_input('input a number:\n')))
print 'orignal number:',number
move(number,n,m)
print 'after moved:',number
22
题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
if __name__ == '__main__':
nmax = 50
n = int(input('please input the total of numbers:'))
num = []
for i in range(n):
num.append(i + 1)
i = 0
k = 0
m = 0
while m < n - 1:
if num[i] != 0 : k += 1
if k == 3:
num[i] = 0
k = 0
m += 1
i += 1
if i == n : i = 0
i = 0
while num[i] == 0: i += 1
print (num[i])
23
#!/usr/bin/python
# -*- coding: UTF-8 -*-
N = 3
#stu
# num : string
# name : string
# score[4]: list
student = []
for i in range(5):
student.append(['','',[]])
def input_stu(stu):
for i in range(N):
stu[i][0] = raw_input('input student num:\n')
stu[i][1] = raw_input('input student name:\n')
for j in range(3):
stu[i][2].append(int(raw_input('score:\n')))
def output_stu(stu):
for i in range(N):
print '%-6s%-10s' % ( stu[i][0],stu[i][1] )
for j in range(3):
print '%-8d' % stu[i][2][j]
if __name__ == '__main__':
input_stu(student)
print student
output_stu(student)
24 指针函数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def peven(n):
i = 0
s = 0.0
for i in range(2,n + 1,2):
s += 1.0 / i
return s
def podd(n):
s = 0.0
for i in range(1, n + 1,2):
s += 1 / i
return s
def dcall(fp,n):
s = fp(n)
return s
if __name__ == '__main__':
n = int(raw_input('input a number:\n'))
if n % 2 == 0:
sum = dcall(peven,n)
else:
sum = dcall(podd,n)
print sum
25 字符串排序
题目:字符串排序。
a = []
n = input("请输入: ")
n = int(n)
while n != 0:
string = input("请输入字符串: ")
a.append(string)
n -= 1
a.sort()
print(a)
26 *(特别算法)
题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
i = 0
j = 1
x = 0
while (i < 5) :
x = 4 * j
for i in range(0,5) :
if(x%4 != 0) :
break
else :
i += 1
x = (x/4) * 5 +1
j += 1
print x
27 列表
题目:列表使用实例。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#list
#新建列表
testList=[10086,'中国移动',[1,2,4,5]]
#访问列表长度
print len(testList)
#到列表结尾
print testList[1:]
#向列表添加元素
testList.append('i\'m new here!')
print len(testList)
print testList[-1]
#弹出列表的最后一个元素
print testList.pop(1)
print len(testList)
print testList
#list comprehension
#后面有介绍,暂时掠过
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print matrix
print matrix[1]
col2 = [row[1] for row in matrix]#get a column from a matrix
print col2
col2even = [row[1] for row in matrix if row[1] % 2 == 0]#filter odd item
print col2even
28 时间函数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
import time
print time.ctime(time.time())
print time.asctime(time.localtime(time.time()))
print time.asctime(time.gmtime(time.time()))
计算时间差。
if __name__ == '__main__':
import time
start = time.clock()
for i in range(400000):
print (i)
end = time.clock()
print ('different is %6.3f' % (end - start))
29 file
if __name__ == '__main__':
fp = open('test.txt','w')
string = input('please input a string:\n')
string = string.upper()
fp.write(string)
fp = open('test.txt','r')
print (fp.read())
fp.close()
当要写的时候,open为‘w’,要读的时候,open为‘r’。