陜西國際商貿(mào)學(xué)院python期末考試題及答案_第1頁
陜西國際商貿(mào)學(xué)院python期末考試題及答案_第2頁
陜西國際商貿(mào)學(xué)院python期末考試題及答案_第3頁
陜西國際商貿(mào)學(xué)院python期末考試題及答案_第4頁
陜西國際商貿(mào)學(xué)院python期末考試題及答案_第5頁
已閱讀5頁,還剩21頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

陜西國際商貿(mào)學(xué)院python期末考試題及答案一、單項選擇題(每題2分,共20分)1.在Python3.11中,下列關(guān)于列表推導(dǎo)式的說法正確的是A.列表推導(dǎo)式內(nèi)部不能使用if條件B.列表推導(dǎo)式會立即生成所有元素,占用內(nèi)存與列表長度成正比C.列表推導(dǎo)式返回的是一個迭代器對象D.列表推導(dǎo)式中不能使用嵌套循環(huán)答案:B解析:列表推導(dǎo)式一次性生成完整列表,內(nèi)存占用與長度成正比;A錯,可使用if;C錯,返回的是list;D錯,可嵌套。2.下列代碼運行后輸出的結(jié)果是```pythondeffoo(x,lst=[]):lst.append(x)returnlstprint(foo(1),foo(2),foo(3,[]),foo(4))```A.[1][1,2][3][1,2,4]B.[1][1,2][3][3,4]C.[1][2][3][4]D.[1][1,2][1,2,3][1,2,3,4]答案:A解析:默認(rèn)參數(shù)lst只在函數(shù)定義時創(chuàng)建一次,后續(xù)調(diào)用共享;第三次調(diào)用傳入新列表,不影響默認(rèn)lst。3.關(guān)于Python裝飾器,以下說法錯誤的是A.裝飾器本身必須是可調(diào)用對象B.使用functools.wraps可保留原函數(shù)元數(shù)據(jù)C.一個函數(shù)可同時被多個裝飾器修飾,離函數(shù)定義最近的先執(zhí)行D.裝飾器只能用于函數(shù),不能用于類答案:D解析:裝飾器也可用于類,如@dataclass。4.下列關(guān)于字典推導(dǎo)式的寫法,能正確生成{"A":1,"B":2,"C":3}的是A.{k:vfork,vinzip("ABC",range(1,4))}B.{chr(i+64):iforiinrange(1,4)}C.dict([(chr(i+64),i)foriinrange(1,4)])D.以上全部答案:D解析:三種寫法均等價。5.在Python中,下列表達(dá)式值為True的是A.[]==FalseB.bool("0")==FalseC.0.1+0.2==0.3D.NoneisNone答案:D解析:A空列表不為False;B非空字符串為True;C浮點誤差;Dis身份比較。6.下列關(guān)于生成器與迭代器的說法正確的是A.生成器是一次性對象,遍歷后需重新創(chuàng)建B.迭代器必須實現(xiàn)__iter__與__next__C.生成器函數(shù)使用returnyield語法D.for循環(huán)無法直接遍歷迭代器答案:A解析:生成器遍歷后耗盡;B錯,迭代器只需__next__;C錯,用yield;D錯,for可直接遍歷迭代器。7.下列代碼運行后x的值是```pythonx=1defouter():x=2definner():globalxx+=1inner()outer()print(x)```A.1B.2C.3D.報錯答案:C解析:inner中聲明globalx,修改的是模塊級x,最終x=2→3。8.下列關(guān)于Python異常處理的說法正確的是A.finally塊中的代碼只有在無異常時才執(zhí)行B.一個except子句可同時捕獲多個異常類型C.raise語句后必須跟異常類,不能跟異常實例D.自定義異常必須繼承BaseException答案:B解析:A錯,finally始終執(zhí)行;C錯,可跟實例;D推薦繼承Exception而非BaseException。9.下列關(guān)于Python內(nèi)存管理的說法錯誤的是A.小整數(shù)池緩存范圍通常為[-5,256]B.列表的append操作時間復(fù)雜度為O(1)C.循環(huán)引用一定導(dǎo)致內(nèi)存泄漏D.gc模塊可手動觸發(fā)垃圾回收答案:C解析:循環(huán)引用可被分代回收檢測并清理,不必然泄漏。10.下列關(guān)于Python類型注解的說法正確的是A.類型注解在運行時會被強制檢查B.List[int]與list[int]完全等價C.使用from__future__importannotations可推遲注解求值D.類型注解無法用于變量,只能用于函數(shù)參數(shù)與返回值答案:C解析:A錯,運行時不檢查;B錯,需從typing導(dǎo)入List;D錯,變量也可注解。二、填空題(每空3分,共30分)11.表達(dá)式`sum(map(lambdax:x*x,range(1,6)))`的值為________。答案:5512.使用collections模塊統(tǒng)計字符串s="abracadabra"中各字符出現(xiàn)次數(shù),代碼為________。答案:collections.Counter(s)13.將列表lst=[1,2,3,4,5]原地逆序,使用切片寫法為________。答案:lst.reverse()或lst[:]=lst[::-1]14.在Python3.11中,使用match語句匹配列表首個元素為0且長度為3的寫法為________。答案:case[0,_,_]:15.使用asyncio創(chuàng)建并發(fā)TCP服務(wù)器,需繼承的基類為________。答案:asyncio.Protocol或asyncio.StreamReaderProtocol(任填一個)16.表達(dá)式`{1,2,3}^{3,4,5}`的結(jié)果為________。答案:{1,2,4,5}17.使用pandas讀取Excel文件需調(diào)用的函數(shù)為________。答案:pandas.read_excel18.將UTC時間字符串"2023-12-01T08:00:00Z"轉(zhuǎn)換為本地時間,需使用的模塊為________。答案:datetime或pytz或zoneinfo(任填一個)19.使用with語句同時打開兩個文件f1、f2的寫法為________。答案:withopen('a.txt')asf1,open('b.txt')asf2:20.在Python中,實現(xiàn)單例模式常用的裝飾器模板中,用于緩存實例的屬性名通常為________。答案:_instance或__instance三、程序閱讀題(每題6分,共30分)21.閱讀程序?qū)懗鲚敵鼋Y(jié)果:```pythonclassA:def__init__(self,v):self.v=vdef__radd__(self,other):returnother+self.v*10a=A(3)print(2+a)```答案:3222.閱讀程序?qū)懗鲚敵鼋Y(jié)果:```pythonimportitertoolsg=itertools.count(1,0.5)print([next(g)for_inrange(5)])```答案:[1,1.5,2.0,2.5,3.0]23.閱讀程序?qū)懗鲚敵鼋Y(jié)果:```pythondefgen():yield1return2g=gen()try:print(next(g))print(next(g))exceptStopIterationase:print(e.value)```答案:1224.閱讀程序?qū)懗鲚敵鼋Y(jié)果:```pythonfromfunctoolsimportlru_cache@lru_cache(maxsize=None)deff(n):returnnifn<2elsef(n-1)+f(n-2)print(f(5),f.cache_info().hits)```答案:5325.閱讀程序?qū)懗鲚敵鼋Y(jié)果:```pythonimportthreadingn=0defadd():globalnfor_inrange(100000):n+=1ts=[threading.Thread(target=add)for_inrange(2)]fortints:t.start()fortints:t.join()print(n)```答案:輸出值小于等于200000的某個不確定值(競態(tài)條件)四、編程題(共70分)26.(15分)文件處理需求:當(dāng)前目錄下存在score.txt,每行格式為"學(xué)號,姓名,語文,數(shù)學(xué),英語",需計算每位學(xué)生的總分,并寫入score_summary.txt,格式為"學(xué)號,姓名,總分",按總分降序排列。要求:使用csv模塊,處理可能缺失的成績(視為0),捕獲并打印文件不存在異常。參考實現(xiàn):```pythonimportcsv,osdefsummary(infile='score.txt',outfile='score_summary.txt'):try:withopen(infile,encoding='utf-8')asfin:reader=csv.reader(fin)rows=[]forsid,name,*scoresinreader:total=sum(int(sor0)forsinscores)rows.append((sid,name,total))rows.sort(key=lambdax:x[2],reverse=True)withopen(outfile,'w',encoding='utf-8',newline='')asfout:csv.writer(fout).writerows(rows)exceptFileNotFoundError:print('文件不存在')if__name__=='__main__':summary()```27.(15分)面向?qū)ο笤O(shè)計一個`Vector2D`類,支持加減、模長、與標(biāo)量乘除、迭代、相等判斷、字符串表示`(x,y)`。要求使用`__slots__`節(jié)省內(nèi)存,支持鏈?zhǔn)秸{(diào)用。參考實現(xiàn):```pythonimportmathclassVector2D:__slots__=('x','y')def__init__(self,x=0,y=0):self.x,self.y=x,ydef__add__(self,other):returnVector2D(self.x+other.x,self.y+other.y)def__sub__(self,other):returnVector2D(self.x-other.x,self.y-other.y)def__mul__(self,k):returnVector2D(self.xk,self.yk)def__truediv__(self,k):returnVector2D(self.x/k,self.y/k)def__abs__(self):returnmath.hypot(self.x,self.y)def__iter__(self):yieldself.x;yieldself.ydef__eq__(self,other):returnself.x==other.xandself.y==other.ydef__repr__(self):returnf'({self.x},{self.y})'測試v1=Vector2D(3,4)v2=Vector2D(1,2)print(v1+v2,abs(v1),v1*2)```28.(20分)算法與數(shù)據(jù)結(jié)構(gòu)實現(xiàn)一個`MinStack`類,支持`push(x)`、`pop()`、`top()`、`getMin()`均為O(1)時間。要求用Python列表模擬棧,不借助外部庫。參考實現(xiàn):```pythonclassMinStack:def__init__(self):self.s=[]self.min_s=[]defpush(self,x):self.s.append(x)ifnotself.min_sorx<=self.min_s[-1]:self.min_s.append(x)defpop(self):ifself.s.pop()==self.min_s[-1]:self.min_s.pop()deftop(self):returnself.s[-1]defgetMin(self):returnself.min_s[-1]測試ms=MinStack()forvin[3,1,2,0]:ms.push(v)print(ms.getMin(),end='')#輸出3110```29.(20分)綜合實踐:異步爬蟲需求:獲取/posts/1~10的標(biāo)題,使用aiohttp并發(fā)請求,將標(biāo)題寫入post_titles.txt,每行一個標(biāo)題,要求超時5秒,捕獲網(wǎng)絡(luò)異常并打印錯誤編號。參考實現(xiàn):```pythonimportaiohttp,asyncio,sysURL='/posts/{}'asyncdeffetch(session,i):try:asyncwithsession.get(URL.format(i),timeout=5)asresp:ifresp.status!=200:raiseValueError(f'status{resp.status}')data=awaitresp.json()returndata['title']exceptExceptionase:print(f'post{i}error:{e}',file=sys.stderr)returnNoneasyncdefmain():asyncwithaiohttp.ClientSession()assession:tasks=[fetch(session,i)foriinrange(1,11)]titles=filter(None,awaitasyncio.gather(*tasks))withopen('post_titles.txt','w',encoding='utf-8')asf:f.write('\n'.join(titles))if__name__=='__main__':asyncio.run(main())```五、設(shè)計題(共50分)30.(50分)校園二手交易小程序后端背景:陜西國際商貿(mào)學(xué)院學(xué)生二手市場需開發(fā)簡易RESTful后端,技術(shù)棧Python+Flask+SQLite,提供商品發(fā)布、搜索、下單、評價功能。要求:1.數(shù)據(jù)庫模型:用戶表(users)、商品表(items)、訂單表(orders)、評價表(reviews),含外鍵約束。2.接口:POST/register注冊POST/login登錄返回JWTGET/items?q=關(guān)鍵字&page=頁碼分頁搜索POST/items發(fā)布商品(需登錄)POST/orders下單(庫存減1)POST/reviews評價3.使用Flask-HTTPAuth驗證,SQLAlchemyORM,Marshmallow序列化,分頁搜索使用聯(lián)合索引。4.提供單元測試覆蓋主要邏輯,使用pytest與Flask測試客戶端。5.代碼需包含異常處理、事務(wù)、防SQL注入、防超賣。參考核心代碼(節(jié)選,完整項目目錄略):```pythonapp.pyfromflaskimportFlask,requestfromflask_sqlalchemyimportSQLAlchemyfromflask_marshmallowimportMarshmallowfromflask_httpauthimportHTTPTokenAuthfromwerkzeug.securityimportgenerate_password_hash,check_password_hashimportjwt,datetime,osapp=Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///trade.db'app.config['SECRET_KEY']=os.urandom(24)db=SQLAlchemy(app)ma=Marshmallow(app)auth=HTTPTokenAuth(scheme='Bearer')classUser(db.Model):id=db.Column(db.Integer,primary_key=True)username=db.Column(db.String(80),unique=True,nullable=False)pw_hash=db.Column(db.String(128))items=db.relationship('Item',backref='seller')classItem(db.Model):id=db.Column(db.Integer,primary_key=True)title=db.Column(db.String(120),index=True)desc=db.Column(db.Text)stock=db.Column(db.Integer,default=1)seller_id=db.Column(db.Integer,db.ForeignKey('user.id'))classOrder(db.Model):id=db.Column(db.Integer,primary_key=True)buyer_id=db.Column(db.Integer,db.ForeignKey('user.id'))item_id=db.Column(db.Integer,db.ForeignKey('item.id'))status=db.Column(db.String(20),default='paid')classReview(db.Model):id=db.Column(db.Integer,primary_key=True)order_id=db.Column(db.Integer,db.ForeignKey('order.id'))score=db.Column(db.Integer)comment=db.Column(db.Text)classUserSchema(ma.SQLAlchemyAutoSchema):classMeta:model=Userexclude=('pw_hash',)user_schema=UserSchema()@auth.verify_tokendefverify(token):try:payload=jwt.decode(token,app.config['SECRET_KEY'],algorithms=['HS256'])returnUser.query.get(payload['uid'])except:returnNone@app.route('/register',methods=['POST'])defregister():data=request.jsonifUser.query.filter_by(username=data['username']).first():return{'msg':'userexists'},400u=User(username=data['username'],pw_hash=generate_password_hash(data['password']))db.session.add(u)mit()returnuser_schema.jsonify(u)@app.route('/login',methods=['POST'])deflogin():data=request.jsonu=User.query.filter_by(username=data['username']).first()ifuandcheck_password_hash(u.pw_hash,data['password']):token=jwt.encode({'uid':u.id,'exp':datetime.datetime.utcnow()+datetime.timedelta(hours=24)},app.config['SECRET_KEY'],algorithm='HS256')return{'token':token}return{'msg':'badcredential'},401@app.route('/items',methods=['GET'])defsearch_items():q=request.args.get('q','')page=int(request.args.get('page',1))pagination=Item.query.filter(Item.title.contains(q)).paginate(page=page,per_page=10,error_out=False)return{'items':[{'id':i.id,'title':i.title,'stock':i.stock}foriinpagination.items],'pages':pagination.pages}@app.route('/items',methods=['POST'])@auth.login_requireddefpost_item():data=request.jsonitem=Item(title=data['title'],desc=data.get('desc',''),stock=data['stock'],seller=auth.current_user())db.session.add(item)mit()return{'id':item.id},201@app.route('/orders',methods=['POST'])@auth.login_requireddefcreate_order():

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論