实例051:按位与
题目: 学习使用按位与 & 。
程序分析: 0&0=0; 0&1=0; 1&0=0; 1&1=1。
a=0o77 print(a) b=a&3 print(b) b=b&7 print(b)
实例052:按位或
题目: 学习使用按位或 | 。
程序分析: 0|0=0; 0|1=1; 1|0=1; 1|1=1
a=0o77 print(a|3) print(a|3|7)
实例053:按位异或
题目: 学习使用按位异或 ^ 。
程序分析: 0^0=0; 0^1=1; 1^0=1; 1^1=0
a=0o77 print(a^3) print(a^3^7)
实例054:位取反、位移动
题目: 取一个整数a从右端开始的4~7位。
程序分析: 可以这样考虑:
- 先使a右移4位。
- 设置一个低4位全为1,其余全为0的数。可用(0<<4)
- 将上面二者进行&运算。
a=int(input('输入一个数字: ')) b=0 # 0 b=~b # 1 b=b<<4 # 10000 b=~b # 1111 c=a>>4 d=c&b print('a:',bin(a)) print('b:',bin(b)) print('c:',bin(c)) print('d:',bin(d))
实例055:按位取反
题目: 学习使用按位取反~。
程序分析: ~0=1; ~1=0;
print(~234) print(~~234)
实例056:画圈
题目: 画图,学用circle画圆形。
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(26): canvas.create_oval(310-k,250-k,310+k,250+k,width=1) k+=j j+=0.3 mainloop()
实例057:画线
题目: 画图,学用line画直线。
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
实例058:画矩形
题目: 画图,学用rectangle画方形。
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()
实例059:画图
题目: 画图,综合例子。
from tkinter import * 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) import math 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()
实例060:字符串长度
题目: 计算字符串长度。
s='zhangguang101' print(len(s))
实例061:杨辉三角
题目: 打印出杨辉三角形前十行。
def generate(numRows): r = [[1]] for i in range(1,numRows): r.append(list(map(lambda x,y:x+y, [0]+r[-1],r[-1]+[0]))) return r[:numRows] a=generate(10) for i in a: print(i)
实例062:查找字符串
题目: 查找字符串。
s1='aabbxuebixuebi' s2='ab' s3='xue' print(s1.find(s2)) print(s1.find(s3))
实例063:画椭圆
题目: 画椭圆。
程序分析: 使用 tkinter。
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()
实例064:画椭圆、矩形
题目: 利用ellipse 和 rectangle 画图。。
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()
实例065:画组合图形
题目: 一个最优美的图案。
import math from tkinter import * 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() if __name__ == '__main__': LineToDemo()
实例066:三数排序
题目: 输入3个数a,b,c,按大小顺序输出。
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) raw2=[] for i in range(3): x=int(input('int%d: '%(i))) raw2.append(x) print(sorted(raw2))
实例067:交换位置
题目: 输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
li=[3,2,5,7,8,1,5] li[-1],li[li.index(min(li))]=li[li.index(min(li))],li[-1] m=li[0] ind=li.index(max(li)) li[0]=li[ind] li[ind]=m print(li)
实例068:旋转数列
题目: 有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
from collections import * li=[1,2,3,4,5,6,7,8,9] deq=deque(li,maxlen=len(li)) print(li) deq.rotate(int(input('rotate:'))) print(list(deq))
实例069:报数
题目: 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
nmax = 50 n = int(input('请输入总人数:')) 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])
实例070:字符串长度II
题目: 写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度。
def lenofstr(s): return len(s) print(lenofstr('tanxiaofengsheng'))
实例071:输入和输出
题目: 编写input()和output()函数输入,输出5个学生的数据记录。
N = 3 #stu #num : string #name : string liststudent = [] for i in range(5): student.append(['','',[]]) def input_stu(stu): for i in range(N): stu[i][0] = input('input student num:\n') stu[i][1] = input('input student name:\n') for j in range(3): stu[i][2].append(int(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)
实例072:创建链表
题目: 创建一个链表。
class Node: def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data class List: def __init__(self, head): self.head = head def is_empty(self): return self.get_len() == 0 def get_len(self): length = 0 temp = self.head while temp is not None: length += 1 temp = temp.next return length def append(self, node): temp = self.head while temp.next is not None: temp = temp.next temp.next = node def delete(self, index): if index < 1 or index > self.get_len(): print("给定位置不合理") return if index == 1: self.head = self.head.next return temp = self.head cur_pos = 0 while temp is not None: cur_pos += 1 if cur_pos == index-1: temp.next = temp.next.next temp = temp.next def insert(self, pos, node): if pos < 1 or pos > self.get_len(): print("插入结点位置不合理") return temp = self.head cur_pos = 0 while temp is not Node: cur_pos += 1 if cur_pos == pos-1: node.next = temp.next temp.next =node break temp = temp.next def reverse(self, head): if head is None and head.next is None: return head pre = head cur = head.next while cur is not None: temp = cur.next cur.next = pre pre = cur cur = temp head.next = None return pre def print_list(self, head): init_data = [] while head is not None: init_data.append(head.get_data()) head = head.next return init_data if __name__=='__main__': head=Node('head') link=List(head) for i in range(10): node=Node(i) link.append(node) print(link.print_list(head))
实例073:反向输出链表
题目: 反向输出一个链表。
class Node: def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data class List: def __init__(self, head): self.head = head def is_empty(self): return self.get_len() == 0 def get_len(self): length = 0 temp = self.head while temp is not None: length += 1 temp = temp.next return length def append(self, node): temp = self.head while temp.next is not None: temp = temp.next temp.next = node def delete(self, index): if index < 1 or index > self.get_len(): print("给定位置不合理") return if index == 1: self.head = self.head.next return temp = self.head cur_pos = 0 while temp is not None: cur_pos += 1 if cur_pos == index-1: temp.next = temp.next.next temp = temp.next def insert(self, pos, node): if pos < 1 or pos > self.get_len(): print("插入结点位置不合理") return temp = self.head cur_pos = 0 while temp is not Node: cur_pos += 1 if cur_pos == pos-1: node.next = temp.next temp.next =node break temp = temp.next def reverse(self, head): if head is None and head.next is None: return head pre = head cur = head.next while cur is not None: temp = cur.next cur.next = pre pre = cur cur = temp head.next = None return pre def print_list(self, head): init_data = [] while head is not None: init_data.append(head.get_data()) head = head.next return init_data if __name__=='__main__': head=Node('head') link=List(head) for i in range(10): node=Node(i) link.append(node) print(link.print_list(head)) print(link.print_list(link.reverse(head)))
实例074:列表排序、连接
题目: 列表排序及连接。
程序分析: 排序可使用 sort() 方法,连接可以使用 + 号或 extend() 方法。
a=[2,6,8] b=[7,0,4] a.extend(b) a.sort() print(a)
实例075:不知所云
题目: 放松一下,算一道简单的题目。
程序分析: 鬼知道是什么。
for i in range(5): n = 0 if i != 1: n += 1 if i == 3: n += 1 if i == 4: n += 1 if i != 4: n += 1 if n == 3: print (64 + i)
实例076:做函数
题目: 编写一个函数,输入n为偶数时,调用函数求1/2+1/4+…+1/n,当输入n为奇数时,调用函数1/1+1/3+…+1/n
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.0 / i return s def dcall(fp,n): s = fp(n) return s if __name__ == '__main__': n = int(input('input a number: ')) if n % 2 == 0: sum = dcall(peven,n) else: sum = dcall(podd,n) print (sum)
实例077:遍历列表
题目: 循环输出列表
l=['moyu','niupi','xuecaibichi','shengfaji','42'] for i in range(len(l)): print(l[i])
实例078:字典
题目: 找到年龄最大的人,并输出。请找出程序中有什么问题。
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]))
实例079:字符串排序
题目: 字符串排序。
l=['baaa','aaab','aaba','aaaa','abaa'] l.sort() print(l)
实例080:猴子分桃
题目: 海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
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) for p in range(5): x=(x-1)/5*4 print(x)
实例081:求未知数
题目: 809*??=800*??+9*?? 其中??代表的两位数, 809*??为四位数,8*??的结果为两位数,9*??的结果为3位数。求??代表的两位数,及809*??后的结果。
a = 809 for i in range(10,100): b = i * a if b >= 1000 and b <= 10000 and 8 * i < 100 and 9 * i >= 100: print(b,' = 800 * ', i, ' + 9 * ', i) for i in range(10,100): if 8*i>99 or 9*i<100: continue if 809*i==800*i+9*i: print(i) break
实例082:八进制转十进制
题目: 八进制转换为十进制
n=eval('0o'+str(int(input('八进制输入:')))) print(n)
实例083:制作奇数
题目: 求0—7所能组成的奇数个数。
程序分析:
- 组成1位数是4个。1,3,5,7结尾
- 组成2位数是7*4个。第一位不能为0
- 组成3位数是784个。中间随意
- 组成4位数是788*4个。
sum = 4 s = 4 for j in range(2,9): print(sum) if j <= 2: s *= 7 else: s *= 8 sum += s print('sum = %d' % sum)
实例084:连接字符串
题目: 连接字符串。
delimiter = ',' mylist = ['Brazil', 'Russia', 'India', 'China'] print(delimiter.join(mylist))
实例085:整除
题目: 输入一个奇数,然后判断最少几个 9 除于该数的结果为整数。
程序分析: 999999 / 13 = 76923。
zi = int(input('输入一个数字:')) n1 = 1 c9 = 1 m9 = 9 sum = 9 while n1 != 0: if sum % zi == 0: n1 = 0 else: m9 *= 10 sum += m9 c9 += 1 print ('%d 个 9 可以被 %d 整除 : %d' % (c9,zi,sum)) r = sum / zi print ('%d / %d = %d' % (sum,zi,r))
实例086:连接字符串II
题目: 两个字符串连接程序。
a='guangtou' b='feipang' print(b+a)
实例087:访问类成员
题目: 结构体变量传递。
class student: x = 0 c = 0 def f(stu): stu.x = 20 stu.c = 'c' a= student() a.x = 3 a.c = 'a' f(a) print(a.x,a.c)
实例088:打印星号
题目: 读取7个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*。
for i in range(3): print('*'*int(input('input a number: ')))
实例089:解码
题目: 某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。
n=input() n = str(n) a=[] for i in range(4): a.append(int(n[i])+5) a[0],a[3]=a[3],a[0] a[1],a[2]=a[2],a[1] print ("".join('%s' %s for s in a))
实例090:列表详解
题目: 列表使用实例。
#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 ) st 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)
实例091:time模块
题目: 时间函数举例1。
import time print(time.ctime(time.time())) print(time.asctime(time.localtime(time.time()))) print(time.asctime(time.gmtime(time.time())))
实例092:time模块II
题目: 时间函数举例2。
程序分析: 如何浪费时间。
import time start = time.time() for i in range(3000): print(i) end = time.time() print (end - start)
实例093:time模块III
题目: 时间函数举例3。
程序分析: 如何浪费时间。
import time start = time.clock() for i in range(100): print(i) end = time.clock() print('different is %6.3f' % (end - start))
实例094:time模块IV
题目: 时间函数举例4。
import time import random play_it = input('do you want to play it.(\'y\' or \'n\')') while play_it == 'y': c = input('input a character:\n') i = random.randint(0,2**32) % 100 print ('please input number you guess:\n') start = time.clock() a = time.time() guess = int(input('input your guess:\n')) while guess != i: if guess > i: print('please input a little smaller') guess = int(input('input your guess:\n')) else: print('please input a little bigger') guess = int(input('input your guess:\n')) end = time.clock() b = time.time() var = (end - start) / 18.2 print (var) # print 'It took you %6.3 seconds' % time.difftime(b,a)) if var < 15: print ('you are very clever!') elif var < 25: print ('you are normal!') else: print ('you are stupid!') print ('Congradulations') print ('The number you guess is %d' % i) play_it = input('do you want to play it.')
实例095:转换时间格式
题目: 字符串日期转换为易读的日期格式。
程序分析: dateutil是个第三方库。
from dateutil import parser dt = parser.parse("Aug 28 2015 12:00AM") print (dt)
实例096:计算复读次数
题目: 计算字符串中子串出现的次数。
s1='xuebixuebixuebixuebixuebixuebixuebixue' s2='xuebi' print(s1.count(s2))
实例097:磁盘写入
题目: 从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止。
from sys import stdout filename = input('输入文件名:\n') fp = open(filename,"w") ch = input('输入字符串:\n') while ch != '#': fp.write(ch) stdout.write(ch) ch = input('') fp.close()
实例098:磁盘写入II
题目: 从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存。
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()
实例099:磁盘读写
题目: 有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中。
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()
实例100:列表转字典
题目: 列表转换为字典。
i = ['a', 'b'] l = [1, 2] print (dict(zip(i,l)))