python必考500题_python练习题

实现1-100的所有的和sum1 = 0

while sum1 

sum1 += 1

print sum1

print ('-----' * 10)

实现1-500所有奇数的和sum1 = 0

for i in xrange(1,501,2):

sum1 += i

print sum1

求1+ 2! + 3! + 4! + ……20!的和a = 1

b = 0

for i in range(1,21):

a = a*i

b = b + a

print(b)

对指定一个list进行排序[2,32,43,453,54,6,576,5,7,6,8,78,7,89]a = [2,32,43,453,54,6,576,5,7,6,8,78,7,89]

a.sort()

print(a)

把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中import ast

import codecs

a = [2,32,43,453,54,6,576,5,7,6,8,78,7,89]

with codecs.open('1.txt','w') as f:

a.sort()

f.write(str(a))

with codecs.open('1.txt','r') as ff:

c = ast.literal_eval(ff.read())

c.reverse()

with codecs.open('1.txt','a') as fff:

fff.write(str(c))

分别把 string, list, tuple, dict写入到文件中import codecs

a = 'abc'

b = [1, 2,]

c = ('a', 'b', 'c',)

d = {'Q':7, 'W':8, 'E':9,}

print(type(a))

print(type(b))

print(type(c))

print(type(d))

with codecs.open('2.txt', 'w') as f:

f.write(str(a))

f.write(str(b))

f.write(str(c))

f.write(str(d))

ABCD*9 = DCBA,使用Python计算abcd分别是哪些数字:class CountNumber(object):

'''ABCD * 9 = DCBA

通过计算机的方法,给我们计算出A = ?  B = ? C = ? D = ?

A: 1-9

B: 0-9

C: 0-9

D: 1-9

A != B != C !=D

'''

def __init__(self):

print("ABCD * 9 = DCBA; A!=B!=C!=D")

def numAbcd(self):

for A in range(1, 10):

for B in range(0, 10):

for C in range(0, 10):

for D in range(1, 10):

if (A*1000 + B*100 + C*10 + D) * 9 == (D*1000 + C*100 + B*10 + A):

print("{0}{1}{2}{3} *9 = {4}{5}{6}{7}".format(A,B,C,D,D,C,B,A))

print("A = {0}, B = {1}, C = {2}, D = {3}".format(A,B, C, D))

def main():

countNumber = CountNumber()

countNumber.numAbcd()

if __name__ == '__main__':

main()

使用Python计算九宫格class NinePaper(object):

def __init__(self):

print('''

_____________

|_A_|_B_|_C_|

|_D_|_E_|_F_|

|_G_|_H_|_I_|

A, B, C, D, E, F, G, H, I 必须是1-9数字,且不能重复

所有的行,列,对角线的和都为15

''')

self.numbers = list()

for i in range(1, 10):

self.numbers.append(i)

print("numbers = {0}".format(self.numbers))

def run(self):

for A in range(1, 10):

l1 = list()

l1 += self.numbers

l1.remove(A)

for B in l1:

l2 = list()

l2 += l1

l2.remove(B)

for C in l2:

l3 = list()

l3 += l2

l3.remove(C)

for D in l3:

l4 = list()

l4 += l3

l4.remove(D)

for E in l4:

l5 = list()

l5 += l4

l5.remove(E)

for F in l5:

l6 = list()

l6 += l5

l6.remove(F)

for G in l6:

l7 = list()

l7 += l6

l7.remove(G)

for H in l7:

l8 = list()

l8 += l7

l8.remove(H)

for I in l8:

if A+B+C == D+E+F == G+H+I == A+D+G == B+E+H == C+F+I == A+E+I == C+E+G == 15:

print('''

_____________

|_{0}_|_{1}_|_{2}_|

|_{3}_|_{4}_|_{5}_|

|_{6}_|_{7}_|_{8}_|

'''.format(A, B, C, D, E, F, G, H, I))

def main():

ninePaper = NinePaper()

ninePaper.run()

if __name__ == '__main__':

main()

passwd文件按uid正序排序 生成一个新的passwd文件,用Python实现import codecs

import os

class SortPasswd(object):

def __init__(self):

self.passwd = "passwd"

self.newpasswd = "newPasswd"

self.contextList = list()

if not os.path.exists(self.passwd):

print("please download passwd from linux.")

exit(1)

print("sort file is :{0}".format(self.passwd))

print("sorted file is :{0}".format(self.newpasswd))

def getContextList(self):

with codecs.open("passwd") as fr:

self.contextList += sorted(fr.readlines(), key=lambda line:int(line.split(":")[2]), reverse=False)

def writeContextList(self):

with codecs.open("new_passwd", "w") as fw:

fw.writelines(self.contextList)

def main():

sortpasswd = SortPasswd()

sortpasswd.getContextList()

sortpasswd.writeContextList()

if __name__ == '__main__':

main()

线程练习题:

定义线程类

import codecs

from queue import Queue

from threading import Thread

import time

class Produce(Thread):

def __init__(self, queue):

super(Produce, self).__init__()

self.fileName = "../firstlession/passwd"

self.fileList = list()

self.queue = queue

def run(self):

with codecs.open(self.fileName) as f:

self.fileList += f.readlines()

for line in self.fileList:

self.queue.put(line)

class Consumer(Thread):

def __init__(self, queue):

self.queue = queue

super(Consumer, self).__init__()

self.newPasswd = "newpasswd.txt"

self.fileList = list()

self.stat = 1

def run(self):

while 1:

if self.queue.empty():

time.sleep(2)

self.stat += 1

if self.stat == 5:

break

else:

self.stat = 1

data = self.queue.get()

self.fileList.append(data)

with codecs.open(self.newPasswd, 'w') as f:

f.writelines(self.fileList)

调用类,并写入主函数

from queue import Queue

from onlive.secondlesson.threadtest import Produce, Consumer

def main():

q = Queue()

produce = Produce(q)

consumer = Consumer(q)

produce.start()

consumer.start()

if __name__ == '__main__':

main()

socket编程

服务端:

from onlive.sockettest.util import SocketServerTest

if __name__ == '__main__':

socketServer = SocketServerTest(host="0.0.0.0", port=9999, type="tcp", backlog=5)

socketServer.run()

客户端:

from onlive.sockettest.util import ClientSocketTest

if __name__ == '__main__':

socketClient = ClientSocketTest(host="127.0.0.1", port=9999, type="tcp")

socketClient.run()

主函数:

import socket

import time

class InitSocketTest(object):

def __init__(self, host, port, type):

self.host = host

self.port = port

self.address = (host, port)

self.type = type

self.s = None

self.creatsocket()

def creatsocket(self):

if self.type.upper() == "TCP":

self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

elif self.type.upper == "UDP":

self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

else:

print("you must input the InitSocket(type) is 'UDP|TCP' ")

class SocketServerTest(InitSocketTest):

def __init__(self, host, port, type,  backlog):

self.backlog = backlog

super(SocketServerTest, self).__init__(host, port, type)

self.clientAddress = None

def run(self):

self.s.bind(self.address)

self.s.listen(self.backlog)

print("server starting…………")

conn, self.clientAddress = self.s.accept()

print("accept connect from {0}".format(self.clientAddress))

for i in range(1, 10):

conn.sendall("i = {0}".format(str(i)).encode("utf-8"))

self.s.close()

class ClientSocketTest(InitSocketTest):

def run(self):

self.s.connect(self.address)

stat = 1

while 1:

data = self.s.recv(2048)

if len(data)>0:

stat = 1

print(data.decode("utf-8"))

else:

stat += 1

time.sleep(1)

if stat == 5:

break

用Python实现ssh客户端

server端

import paramiko

import time

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 上面是用来设置known-host

host = "192.168.48.131"

port = 22

username = "root"

passwd = "123456"

client.connect(hostname=host, port=port, username=username, password=passwd)

stat = 1

while 1:

cmd = input("{0}>> ".format(host))

if cmd:

stat = 1

stdin, stdout, stderr = client.exec_command(cmd)

for std in stdout.readlines():

print(std)

else:

stat += 1

time.sleep(1)

if stat == 5:

break

client端

import socket

import time

if __name__ == '__main__':

host = "192.168.48.131"

port = 12345

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, port))

stat = 1

while 1:

cmd = input("{0}>>> ".format(host))

if cmd.lower() == "exit":

exit()

if not cmd:

continue

s.sendall(cmd.encode("utf-8"))

data = s.recv(2048)

redata = data.decode("utf-8").replace("\n", "\r\n")

# print(type(data))

if len(data)>0:

stat = 1

print("{0}".format(redata))

else:

stat += 1

time.sleep(1)

if stat == 5:

break

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值