1. Randomly generate 20 two-bit positive integers, sort them in ascending order and then write to the text file Data_asc.txt!
1 ImportRandom2Alist = [Random.randint (10,100) forIinchRange (20)]#randomly generate 202-bit integers3Alist.sort ()#from small to large ascending4Date =[str (i) +'\ n' forIinchAlist]5With open (r'D:\data_asc.txt','W') as FP:#Open File6Fp.writelines (date)#Write a file
2, define a function is_prime (n), determine whether the input n is a prime number, is the words return True, otherwise return False. Enter two integers x and Y through the keyboard , calling this
1 ImportMath2 defIs_prime (n):#function of judging prime number3 ifN<2:4 return05 forIinchRange (2,int (MATH.SQRT (n)) +1):6 ifn%i = =0:7 return08 return19 TenWith open ('In.txt','R') as fin: OneData=Fin.read () Adatalist=Data.split () -datalist=map (int,datalist) -x,y=DataList the - ifX>y: -x,y=y,x -s=0 + forIinchRange (x,y+1): - ifIs_prime (i): +S=s+1 AWith open ('OUT.txt','W') as Fout: at Fout.write (str (s)) -
The function outputs the number of primes within the range of two numbers (including x and Y). Using the file implementation, the X and Y representations of the range are placed in the in.txt file, and the results are output in the out.txt file.
Python Practice-Files