Python练习题
冒泡排序
def bubbleSort(list):
for i in range(len(list)):
for j in range(i,len(list)):
if list[i] > list[j]:
list[i],list[j] = list[j],list[i]
print list
求100以内的质数的倒数和
def prime(x):
list = []
for i in range(2,x):
for j in range(2,i):
if i%j == 0 :
break
else:
list.append(i)
return list
if __name__=='__main__':
list = prime(100)
print list
sum = 0
for i in range(len(list)):
sum += 1/float(list[i])
print sum
斐波那契数列
#递归
def fibonacci2(first,second,n):
if n == 0 :
return first
elif n == 1:
return second
else:
return fibonacci2(first,second,n-1)+fibonacci2(first,second,n-2)
if __name__=="__main__":
for i in range(10):
print(fibonacci2(1,1,i))
#迭代
def fibonacci(first,second,n):
#result = 0
#do something
if n == 0 :
return first
elif n == 1:
return second
else:
#sum = first + second
sum = 0
for i in range(n):
sum = first + second
first,second = second,sum
return sum
if __name__=="__main__":
for i in range(10):
print(fibonacci(1,1,i))
最大公约数
def gcd(self,m,n):
if not n:
return m
else:
return self.gcd(n,m%n)
最小公倍数
def lcm2(self,x,y):
if x*y == 0:
return 0
else:
return int(x*y/self.gcd(x,y))
def lcm3(self,x,y):
if x*y == 0:
return 0
if x > y:
greater = x
else:
greater = y
while greater%x or greater %y:
greater+=1
return greater
字符串翻转
s = "happy"
print s[::-1]
打开文档
file = open(“filename”,“rwx”)
打开excel
import
xlwt
book
=
xlwt.Workbook(encoding
=
'utf-8'
, style_compression
=
0
)
快速排序
def quick_sort(qlist):
if qlist == []:
return []
else:
qfirst = qlist[0]
qless = quick_sort([l for l in qlist[1:] if l < qfirst])
qmore = quick_sort([m for m in qlist[1:] if m >= qfirst])
return qless + [qfirst] + qmore
qlist = quick_sort([4,5,6,7,3,2,6,9,8])
print qlist
#返回n以内所有数的阶乘的和
def fn(n):
if n==1 :
return 1
else:
return n*fn(n-1)
#求一个数的质因数
def zhiyinshu(m):
if m<2:
exit(0)
else:
for i in range(2,m+1):
if m%i==0:
print i
return zhiyinshu(m/i)
#鸡兔同笼
总数x只,脚y只
def jitu(x,y):
for ji in range(x+1):
for tu in range(x+1):
if (2 * ji + 4 * tu == y) and(ji+tu == x):
print ji,tu
jitu(35,94)