python题目练习
1、随机生成一个大文件(5G以上),查找里面内容最长的N(N>5)行,并打印出来
[root@saltstack-ui ~]# cat gen_large_file.py
import os
with open("a.txt", "w") as f:
f.write(os.urandom(1024*1024*1024*5)) # 产生一个5G大小的文件,里面都是随机内容,耗时长,有待改进
[root@saltstack-ui ~]# cat find_large_line.py # 利用list sort来排列,然后打印最长的5行
log_path='a.txt'
N=5
with open(log_path) as f:
a = [ line for line in f ]
a.sort(key=lambda x:len(x),reverse=True)
for i in range(N):
print "%d %s" %(i+1,a[i])
# 下面看种省内存的实现:
try:
with open(log_path) as f:
for line in f:
aList.append(line)
aList.sort(key=lambda x:len(x),reverse=True)
if len(aList) > N:
del aList[N:]
except ioError:
print "IO error"
2、打印1000以内的最大斐波那契数列
# 使用递归
N=0
def fib1(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib1(n-1) + fib1(n-2)
while fib1(N) < 1000:
print fib1(N)
N +=1
# 使用递归(优化:算完的不用再算)
N=0
mem = {0:0 , 1:1}
def fib2(n):
if n not in mem:
mem[n] = fib2(n-1) + fib2(n-2)
return mem[n]
while fib2(N) < 1000:
print fib2(N)
N +=1
# 使用了迭代器
def fib3(n):
a, b = 0,1
while a < n:
yield a
a,b = b,a+b
for i in fib3(1000):
print i
3、python实现linux tail -f
[root@saltstack-ui PyTest]# cat tail_f.py
import time
def tail_f(file):
interval = 1
while True:
line = file.readline()
if not line:
time.sleep(interval)
where = file.tell()
file.seek(where)
else:
yield line
for line in tail_f(open('a.txt')):
print line,
4、Python实现栈、队列(基于List实现)
class Stack():
def __init__(self):
self.stack = []
def push(self,item):
self.stack.append(item)
def pop(self):
if self.stack != []:
return self.stack.pop(-1)
def top(self):
if self.stack != []:
return self.stack[-1]
else:
return None
def length(self):
return len(self.stack)
class Queue():
def __init__(self):
self.queue = []
def enq(self,item):
self.queue.append(item)
def deq(self):
if self.queue != []:
return self.queue.pop(0)
def head(self):
if self.queue != []:
return self.queue[0]
def tail(self):
if self.queue != []:
return self.queue[-1]
def length(self):
return len(self.queue)
python collections模块提供了deque双向队列数据结构,双向都可以出队列
python实现环形队列,基于一个定长的list实现
class RingQueue:
def __init__(self,capacity):
self.size = 0
self.front = 0
self.end = 0
self.capacity = capacity
self.queue = [0] * capacity
def enq(self,item):
if self.size < self.capacity:
self.size += 1
self.queue[self.end] = item
self.end = (self.end + 1) % self.capacity
else:
print "The queue is full!"
def dep(self):
if self.size > 0:
self.size -= 1
self.queue[self.front] = 0
self.front = (self.front + 1) % self.capacity
else:
print "The queue is empty!"
def get_front(self):
return self.queue[self.front]
if __name__ == '__main__':
ringqueue = RingQueue(3)
ringqueue.enq('1')
print ringqueue.queue
ringqueue.enq('2')
print ringqueue.queue
ringqueue.dep()
print ringqueue.queue
ringqueue.enq('3')
print ringqueue.queue
ringqueue.dep()
print ringqueue.queue
ringqueue.enq('4')
print ringqueue.queue
ringqueue.enq('5')
print ringqueue.queue
相关文章