题目 编写一个函数,输入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)
题目 找到年龄最大的人,并输出。请找出程序中有什么问题。是不是很巧妙的解决了问题
if __name__ == '__main__':
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]))
创建链表
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))
反向输出链表
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)))
输入和输出
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] = 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)
题目 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
if __name__ == '__main__':
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])
输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
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)
输入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))
题目 一个最优美的图案。
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()
作用域、类的方法与变量
class dummy:
num=1
def Num(self):
print('class dummy num:',self.num)
print('global num: ',num)
self.num+=1
n=dummy()
num=1
for i in range(5):
num*=10
n.Num()
变量作用域
i=0
n=0
def dummy():
i=0
print(i)
i+=1
def dummy2():
global n
print(n)
n+=1
print('函数内部的同名变量')
for j in range(20):
print(i)
dummy()
i+=1
print('global声明同名变量')
for k in range(20):
print(n)
dummy2()
n+=10
求100之内的素数。
lo=int(input('下限:'))
hi=int(input('上限:'))
for i in range(lo,hi+1):
if i > 1:
for j in range(2,i):
if (i % j) == 0:
break
else:
print(i)
题目 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
def age(n):
if n==1:
return 10
return 2+age(n-1)
print(age(5))
求1+2!+3!+…+20!的和。
res=1
for i in range(20,1,-1):
res=i*res+1
print(res)
猴子偷桃
题目 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
程序分析 按规则反向推断:猴子有一个桃子,他偷来一个桃子,觉得不够又偷来了与手上等量的桃子,一共偷了9天。
peach=1
for i in range(9):
peach=(peach+1)*2
print(peach)
题目 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
high=200.
total=100
for i in range(10):
high/=2
total+=high
print(high/2)
print('总长:',total)
题目 一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
def factor(num):
target=int(num)
res=set()
for i in range(1,num):
if num%i==0:
res.add(i)
res.add(num/i)
return res
for i in range(2,1001):
if i==sum(factor(i))-i:
print(i)
题目 将一个整数分解质因数。例如:输入90,打印出90=233*5。
target=int(input('输入一个整数:'))
print(target,'= ',end='')
if target<0:
target=abs(target)
print('-1*',end='')
flag=0
if target<=1:
print(target)
flag=1
while True:
if flag:
break
for i in range(2,int(target+1)):
if target%i==0:
print("%d"%i,end='')
if target==i:
flag=1
break
print('*',end='')
target/=i
break
题目 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
for i in range(100,1000):
s=str(i)
one=int(s[-1])
ten=int(s[-2])
hun=int(s[-3])
if i == one**3+ten**3+hun**3:
print(i)
题目 判断101-200之间有多少个素数,并输出所有素数。
程序分析 判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。 用else可以进一步简化代码.
import math
for i in range(100,200):
flag=0
for j in range(2,round(math.sqrt(i))+1):
if i%j==0:
flag=1
break
if flag:
continue
print(i)
print('\nSimplify the code with "else"\n')
for i in range(100,200):
for j in range(2,round(math.sqrt(i))+1):
if i%j==0:
break
else:
print(i)
题目 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析 我认为原文的解法有点扯,没有考虑3个月成熟的问题,人家还是婴儿怎么生孩子?考虑到三个月成熟,可以构建四个数据,其中:一月兔每个月长大成为二月兔,二月兔变三月兔,三月兔变成年兔,成年兔(包括新成熟的三月兔)生等量的一月兔。
month=int(input('繁殖几个月?: '))
month_1=1
month_2=0
month_3=0
month_elder=0
for i in range(month):
month_1,month_2,month_3,month_elder=month_elder+month_3,month_1,month_2,month_elder+month_3
print('第%d个月共'%(i+1),month_1+month_2+month_3+month_elder,'对兔子')
print('其中1月兔:',month_1)
print('其中2月兔:',month_2)
print('其中3月兔:',month_3)
print('其中成年兔:',month_elder)