#第二题,做一个加减乘除的考试系统,自动出题,自动判对错,并统计结果,一次考试10道题 import random symbols=["+","-","*","/"] total_count=0 correct_count=0 incorrect_count=0 while 1: random_number1=random.randint(0,11) random_number2=random.randint(0,11) random_symbol=random.choice(symbols) if random_symbol=="/" and random_number2==0: continue elif random_symbol=="/" and random_number1%random_number2 !=0: continue expression=str(random_number1)+" "+random_symbol+" "+str(random_number2) answer=eval(expression) print expression,"= ", while 1: try: user_answer=int(raw_input("")) break except: print "input is not a number,try again" if user_answer==answer: print "your answer is right" correct_count+=1 total_count+=1 else: print "your answer is wrong,the right answer is %s" %answer incorrect_count+=1 total_count+=1 if total_count==3: break print "correct answer is %s" %correct_count print "incorrect answer is %s" %incorrect_count #第三题:计算一个二维矩阵的正对角线、反对角线、周边数之和 a=[ [1,2,3], [4,5,6], [7,8,9] ] #遍历正对角线 count=0 for i in range(len(a)): for j in range(len(a[0])): if i==j: count+=a[i][j] print count #遍历反对角线 #[0][2] #[1][1] #[2][0] count=0 column=len(a[0])-1 for i in range(len(a)): count+=a[i][column-i] print count #周边元素和 #[0][0] #[0][1] #[0][2] #[1][0] #[1][2] #[2][0] #[2][1] #[2][2] count=0 for i in range(len(a)): for j in range(len(a[0])): if i==0 or i==len(a)-1 or j==0 or j==len(a[0])-1: print i,j count+=a[i][j] print count #练习:加锁 from multiprocessing import Process,Lock import time def lock_lock(lock,num): lock.acquire() time.sleep(0.2) print "hello Num: %s" %num lock.release() if __name__=="__main__": lock=Lock() for num in range(20): p=Process(target=lock_lock,args=(lock,num)) p.start() #练习:多进程写一个文件,加锁 from multiprocessing import Process,Lock import time def write(lock,num): lock.acquire() with open("e:\text40.txt","a+") as f: f.write("wangjing:%s " %(num)) lock.release() if __name__=="__main__": lock=Lock() for i in range(5): p=Process(target=write,args=(lock,i)) p.start() p.join() print "write file done" #练习:多把锁 import multiprocessing import time def worker(s, i): s.acquire() print(multiprocessing.current_process().name + " acquire") time.sleep(i) print(multiprocessing.current_process().name + " release") s.release() if __name__ == "__main__": # 设置限制最多3个进程同时访问共享资源 s = multiprocessing.Semaphore(3) for i in range(5): p = multiprocessing.Process(target = worker, args = (s, i * 2)) p.start()