2025年Python编程挑战专项训练试卷 模拟实战测评版_第1页
2025年Python编程挑战专项训练试卷 模拟实战测评版_第2页
2025年Python编程挑战专项训练试卷 模拟实战测评版_第3页
2025年Python编程挑战专项训练试卷 模拟实战测评版_第4页
2025年Python编程挑战专项训练试卷 模拟实战测评版_第5页
已阅读5页,还剩10页未读 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

2025年Python编程挑战专项训练试卷模拟实战测评版考试时间:______分钟总分:______分姓名:______第一题编写一个Python函数`find_largest_prime_factors(n)`,接收一个正整数`n`作为参数。函数需要找出并返回`n`的所有质因数,并将这些质因数按从大到小的顺序排列成一个列表。如果`n`小于2,函数返回一个空列表。例如:*`find_largest_prime_factors(13195)`应返回`[29,23,5,7]`*`find_largest_prime_factors(2048)`应返回`[2]`*`find_largest_prime_factors(1)`应返回`[]`第二题现有以下字符串列表`sentences`:```pythonsentences=["Pythonisaninterpretedhigh-levelgeneral-purposeprogramminglanguage.","Python'sdesignphilosophyemphasizescodereadabilitywithitsnotableuseofsignificantwhitespace.","Pythonisdynamically-typedandgarbage-collected.","Pythonsupportsmultipleprogrammingparadigms,includingstructured(particularlyprocedural),object-orientedandfunctionalprogramming."]```请编写代码,创建一个新的列表`word_frequencies`。该列表中的每个元素都是一个字典,字典的键是单词(不区分大小写,且已去除标点符号),值是该单词在所有句子中出现的总次数。按单词在总词频中从高到低的顺序排列`word_frequencies`列表。第三题编写一个生成器函数`generate_powerset(s)`,接收一个集合`s`作为参数。该函数需要生成并依次yield`s`的所有子集(幂集),包括空集和`s`本身。子集应保持原始集合中元素的顺序。例如,如果输入`s={1,2,3}`,生成器应按以下顺序yield子集:`{}`,`{1}`,`{2}`,`{1,2}`,`{3}`,`{1,3}`,`{2,3}`,`{1,2,3}`第四题假设你需要处理一个大型日志文件,该文件每行包含一个JSON格式的日志记录,记录中可能包含嵌套的字典或列表。日志记录的格式大致如下(示例):```json{"time":"2023-10-27T10:00:00Z","level":"INFO","message":"Userloggedin.","details":{"user_id":123,"session_id":"abcde"}}{"time":"2023-10-27T10:01:05Z","level":"ERROR","message":"Filenotfound.","details":[{"error":"ENOENT","code":2},{"path":"/var/log/app.log"}]}```请编写一个函数`process_log_entries(log_file_path)`。该函数接收一个表示日志文件路径的字符串`log_file_path`。函数需要按行读取文件,尝试解析每一行的JSON内容。如果解析成功,函数应统计并返回一个字典,该字典包含两个键:`'INFO'`和`'ERROR'`,对应的值是相应级别日志记录的数量。如果某行JSON解析失败(例如格式错误),应捕获异常,并忽略该行,继续处理下一行。如果文件不存在或无法读取,函数应抛出`IOError`异常。第五题请编写一个类`CircularBuffer`,实现一个固定大小的循环缓冲区。该缓冲区支持以下方法:*`__init__(self,capacity)`:初始化缓冲区,设置其容量`capacity`。内部可以使用列表`self._data`和两个指针`self._head`(指向第一个有效元素)和`self._tail`(指向下一个插入位置)来实现。*`enqueue(item)`:将元素`item`添加到缓冲区的末尾(`self._tail`指向的位置)。如果缓冲区已满,应覆盖最早添加的元素(即`self._head`指向的元素)。*`dequeue()`:从缓冲区的头部(`self._head`指向的位置)移除并返回一个元素。如果缓冲区为空,返回`None`。*`size(self)`:返回缓冲区中当前元素的数量。*`is_empty(self)`:如果缓冲区为空,返回`True`;否则返回`False`。*`is_full(self)`:如果缓冲区已满,返回`True`;否则返回`False`。请确保你的实现能够正确处理循环的情况。第六题编写一个函数`find_closest_pairs(points)`,接收一个二维点列表`points`作为参数,其中每个点表示为`(x,y)`坐标对。函数的目标是找出所有距离最近的点对(至少有两个点)。对于每一对距离最近的点,返回它们之间的欧几里得距离的平方(即`distance_squared=(x2-x1)^2+(y2-y1)^2`)。结果应是一个列表,其中包含所有最近点对的距离平方,按从小到大的顺序排列。如果有多个点对的距离相同且为最小值,应全部包含在结果列表中。例如:*`find_closest_pairs([(0,0),(1,0),(1,1),(0,1)])`应返回`[0,1,1]`(点(0,0)和(0,1)距离为0,点(0,0)和(1,0)以及(0,1)和(1,1)距离为1)*`find_closest_pairs([(1,2),(3,4),(5,6),(7,8)])`应返回`[2,2,2]`(所有点对距离均为2)试卷答案第一题```pythondeffind_largest_prime_factors(n):ifn<2:return[]factors=[]#Handlefactor2separatelytoallowincrementingby2laterwhilen%2==0:factors.append(2)n//=2#Checkoddfactorsfrom3onwardsi=3whilei*i<=n:whilen%i==0:factors.append(i)n//=ii+=2#Ifnisaprimenumbergreaterthan2ifn>2:factors.append(n)#Returnfactorssortedindescendingorderreturnsorted(factors,reverse=True)```解析思路:首先处理特殊情况n<2,直接返回空列表。对于n=2,返回[2]。对于其他数,使用试除法找质因数。先去除所有因子2,然后从3开始,只检查奇数因子(因为偶数已被处理),直到检查到平方根。如果最后n大于2,则n本身是一个质因数。最后将找到的所有质因数按降序排列并返回。第二题```pythonfromcollectionsimportdefaultdictimportstringsentences=["Pythonisaninterpretedhigh-levelgeneral-purposeprogramminglanguage.","Python'sdesignphilosophyemphasizescodereadabilitywithitsnotableuseofsignificantwhitespace.","Pythonisdynamically-typedandgarbage-collected.","Pythonsupportsmultipleprogrammingparadigms,includingstructured(particularlyprocedural),object-orientedandfunctionalprogramming."]word_frequencies=[]#Createasetofalluniquewordsafterpreprocessing#Preprocess:lowercase,removepunctuationwords_set=set()forsentenceinsentences:#Removepunctuationusingstr.translatetranslator=str.maketrans('','',string.punctuation)cleaned_sentence=sentence.lower().translate(translator)words=cleaned_sentence.split()words_set.update(words)#Initializefrequencydictionaryfreq_dict={word:0forwordinwords_set}#Countwordoccurrencesforsentenceinsentences:translator=str.maketrans('','',string.punctuation)cleaned_sentence=sentence.lower().translate(translator)words=cleaned_sentence.split()forwordinwords:ifwordinfreq_dict:freq_dict[word]+=1#Createlistof(word,freq)tuplesword_freq_list=[(word,freq_dict[word])forwordinwords_set]#Sortthelistbyfrequencyindescendingorderword_freq_list.sort(key=lambdax:x[1],reverse=True)#Createthefinallistofdictionariesword_frequencies=[{'word':item[0],'count':item[1]}foriteminword_freq_list]```解析思路:首先遍历所有句子,将每个句子转换为小写,并去除标点符号,然后分割成单词列表。使用集合`words_set`收集所有唯一的单词。然后,创建一个默认字典`freq_dict`来存储每个单词的总出现次数,初始化为0。再次遍历所有句子,更新`freq_dict`中单词的计数。最后,将`freq_dict`转换为包含单词和计数的元组列表`word_freq_list`,按计数降序排序,再将排序后的列表转换为所需的字典列表格式。第三题```pythondefgenerate_powerset(s):#Sortthesetforconsistentorderofsubsetss_list=sorted(s)n=len(s_list)#Totalnumberofsubsetsis2^n#Usebitmaskfrom0to2^n-1foriinrange(2n):subset=[]forjinrange(n):#Checkifthej-thbitinbitmaskiissetifi&(1<<j):subset.append(s_list[j])yieldset(subset)#Exampleusage(notpartoftherequiredfunction):#s={1,2,3}#forsubsetingenerate_powerset(s):#print(subset)```解析思路:幂集是集合所有可能的子集的集合,包括空集和集合本身。对于一个包含n个元素的集合,其幂集大小为2^n。可以使用二进制位掩码来生成所有可能的组合。从0到2^n-1遍历每个整数,将整数看作一个二进制位掩码,其中第j位为1表示集合中第j个元素(按排序顺序)包含在当前子集中。通过检查位掩码的每一位是否为1,可以构建出对应的子集,然后yield出来。为了保持子集的顺序,输入集合先进行排序。第四题```pythonimportjsondefprocess_log_entries(log_file_path):info_count=0error_count=0try:withopen(log_file_path,'r')asfile:forlineinfile:try:log_data=json.loads(line)#Checkthe'level'fieldlog_level=log_data.get('level','').upper()iflog_level=='INFO':info_count+=1eliflog_level=='ERROR':error_count+=1exceptjson.JSONDecodeError:#IgnorelinesthatarenotvalidJSONcontinueexceptIOError:#RaiseIOErroriffilecannotbeopened/readraiseIOError(f"Couldnotopenorreadfile:{log_file_path}")return{'INFO':info_count,'ERROR':error_count}```解析思路:函数需要按行读取文件,对每行尝试解析JSON。成功解析后,检查日志数据的`level`字段。如果`level`是`'INFO'`,则`info_count`加1;如果是`'ERROR'`,则`error_count`加1。如果某行JSON解析失败(`json.loads`抛出`JSONDecodeError`),捕获该异常并忽略该行,继续处理下一行。如果文件本身无法打开或读取(如路径错误、权限问题),捕获`IOError`并重新抛出,明确告知调用者。最后返回一个包含`INFO`和`ERROR`计数的字典。第五题```pythonclassCircularBuffer:def__init__(self,capacity):self.capacity=capacityself._data=[None]*capacityself._head=0self._tail=0self._size=0defenqueue(self,item):ifself.is_full():#Overwritetheelementatheadself._data[self._head]=item#Moveheadforward(circularly)self._head=(self._head+1)%self.capacityelse:#Additemattailself._data[self._tail]=item#Movetailforwardself._tail=(self._tail+1)%self.capacityself._size+=1defdequeue(self):ifself.is_empty():returnNone#Getitemfromheaditem=self._data[self._head]#Resettheitematheadself._data[self._head]=None#Moveheadforwardself._head=(self._head+1)%self.capacityself._size-=1returnitemdefsize(self):returnself._sizedefis_empty(self):returnself._size==0defis_full(self):returnself._size==self.capacity```解析思路:循环缓冲区使用固定大小的数组实现。需要两个指针:`_head`指向队列头部(下一个出队元素的位置),`_tail`指向队列尾部(下一个入队元素的位置)。维护一个`_size`变量跟踪当前元素数量。`enqueue`:如果缓冲区已满,则需要覆盖最早添加的元素(即`_head`指向的元素),然后将新元素添加到`_tail`指向的位置,并移动`_tail`。如果缓冲区未满,直接添加元素到`_tail`,移动`_tail`并增加`_size`。`dequeue`:如果缓冲区为空,返回`None`。否则,从`_head`指向的位置取出元素,重置该位置(设为`None`),移动`_head`并减少`_size`。`size`返回`_size`。`is_empty`检查`_size`是否为0。`is_full`检查`_size`是否等于容量`capacity`。指针移动需要使用模运算`%`以实现循环。数组初始化为`None`有助于判断位置是否被占用。第六题```pythonimportmathdeffind_closest_pairs(points):iflen(points)<2:return[]#HelperfunctiontocalculateEuclideandistancesquareddefdistance_squared(p1,p2):return(p1[0]-p2[0])2+(p1[1]-p2[1])2#Sortpointsprimarilybyx,thenbyycoordinatesorted_points=sorted(points,key=lambdap:(p[0],p[1]))#Helperfunctiontofindminimumdistanceinstripusingtwopointersdefmin_distance_in_strip(strip,d):min_d=dstrip.sort(key=lambdap:p[1])#Sortstripbyy-coordinateforiinrange(len(strip)):j=i+1#Onlycheckpairswherethey-distanceislessthancurrentmin_dwhilej<len(strip)and(strip[j][1]-strip[i][1])<min_d:dist=distance_squared(strip[i],strip[j])ifdist<min_d:min_d=distj+=1returnmin_d#Recursivefunctiontofindminimumdistancedefclosest_util(points_sorted):num_points=len(points_sorted)ifnum_points<=3:#Forsmallnumberofpoints,computeallpairwisedistancesmin_d=float('inf')foriinrange(num_points):forjinrange(i+1,num_points):dist=distance_squared(points_sorted[i],points_sorted[j])ifdist<min_d:min_d=distreturnmin_d#Dividepointsintotwohalvesmid=num_points//2mid_x=points_sorted[mid][0]#Recursivelyfindthesmallestdistancesinleftandrighthalvesd_left=closest_util(points_sorted[:mid])d_right=closest_util(points_sorted[mid:])d=min(d_left,d_right)#Createthestripcontainingpointsclosetothemiddlelinestrip=[]forpointinpoints_sorted:ifabs(point[0]-mid_x)<d:strip.append(point)#Findtheclosestpointsinthestripmin_d_strip=min_distance_in_strip(strip,d)#Returntheminimumofd,d_left,d_right,andmin_d_stripreturnmin(d,min_d_strip)#Gettheminimumdistanceusingthedivideandconquerapproachmin_distance=closest_util(sorted_points)#Collectalldistancesthatare

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论