CUIT 軟件工程學院2019級Python習題練習2
判斷題
1-1 open("test.txt", 'r+')是以只讀模式打開test.txt文件。(F)
1-2 使用Python內置的open函數打開某個文件的時候,如果該文件不存在,則可能產生異常。所以一定要使用try except對其進行處理。(F)
1-3 在定義函數時,某個參數名字前面帶有兩個符號表示可變長度參數,可以接收任意多個關鍵參數並將其存放於一個字典之中(T)
1-4 在編寫函數時,建議首先對形參進行類型檢查和數值范圍檢查之后再編寫功能代碼,或者使用異常處理結構,盡量避免代碼拋出異常而導致程序崩潰。(T)
1-5 只有Python擴展庫才需要導入以后才能使用其中的對象,Python標准庫不需要導入即可使用其中的所有對象和方法。(F)
1-6 對文件進行讀寫操作之后必須顯式關閉文件以確保所有內容都得到保存。(T)
1-7 二進制文件不能使用記事本程序打開。(F)
1-8 使用random模塊的函數randint(1, 100)獲取隨機數時,有可能會得到100。(T)
1-9 Python中類內部定義的私有屬性絕對不能為類外部訪問(T)
1-10 對於如下代碼,Test類的name為對象屬性,id與age為類屬性。(F)
class Test:
name = "default"
def __init__(self, id, age):
self.id = id
self.age = age
單選題
2-1 已知x=[1,3,5]、y=[2,4,6],則x+y的結果是__C___。
A.[2, 4, 6, 1, 3, 5] B.[1, 2, 3, 4, 5, 6]
C.[1, 3, 5, 2, 4, 6] D.[6, 5, 4, 3, 2, 1]
2-2
語句x = 3==3, 5執行結束后,變量x的值為____C___。
A.(3, 5) B.3
C.(True, 5) D.5
2-3
下列選項中,能求出x和y中最小值,並賦值給min的是__A___。
A.min = x if x < y else y B.min = x < y ? x : y
C.if x < y: min=x D.if (x<y): x, y = y, x
2-4
對於字典dic={1:2, '3': 'd', 'd':2, 4:{1:2, 2:3} }, len(dic)的值是(B)
A.3 B.4
C.5 D.6
2-5
print(type({})) 的輸出結果是(A)
A.<class 'dict'> B.<class 'list'>
C.<class 'set'> D.<class 'str'>
2-6
已知d是個空字典,執行下列語句后,會產生錯誤的是(B)
A.d.get(1,2) B.print(d[1])
C.d[1]=2 D.1 in d
2-7
已知d={1 : 2, '3' : 4},下列修改字典的方式中,錯誤的是(D)
A.d.update({3:1}) B.d[3]=1
C.d['3']=1 D.d.get('3')=1
2-8
已知列表x=list(range(1,6)),下列選項中可以取出最后一個元素的操作有__C_____
A.x[5] B.x[6]
C.x[4] D.x[len(x)]
2-9
已知 aList = [1,2,3,4,5,6,7],下列說法中錯誤的是B
A.aList[:100]的值與a[:]的值相等 B.aList[100]的值為[]
C.aList[:-100]的值為[] D.aList[3:-3]的值是[4]
2-10
下列表達式的值是True的有(C)
A.[3] in [1,2,3] B.3 in [123]
C.'3' in list('123') D.3 in list('123')
2-11
下列選項中與s[ : -1 ]的值相同的是(D)
A.s[-1] B.s[:]
C.s[:len(s)] D.s[0:len(s)-1]
2-12
下列哪個操作無法對字符串使用(A)
A.分片 B.合並
C.索引 D.賦值
2-13
下列哪個關於字符串的描述是正確的(D)
A.字符串a的最后一個字母是a[ : -1] B.字符串中同一個字母大小寫沒有區別
C.Python3中字符串的默認字符編碼是utf-8 D.兩個字符串不可以比較大小
2-14
表達式: "4"+5的結果是(C)
A.9 B."9"
C.“45” D.出錯
2-15
已知s="abcdefg",下面哪個說法是錯誤的(B)
A.s[::2]的值為'aceg' B.s[:-1:2]的值為''
C.s[:1:]的值為'a' D.s[-1:0:-1]的值為'gfedcb'
填空題
4-1
Python內置函數open 用____打開文件表示讀模式。'r'
4-2
對文件進行寫入操作之后,_____方法用來在不關閉文件對象的情況下將緩沖區內容寫入文件。flush()
4-3
已知函數定義 def func(x):return x%2==1, 那么表達式 filter(func,[10,8,9,4,3,1])的值為____。[9, 3, 1]
4-4
已知 x = 3,那么執行語句 x *= 6 之后,x的值為___18
4-5
已知s1="Windows10",s2="Python3.7",則執行result=''.join(filter(lambda x:x.isdigit(), s1+s2))之后,result的值為_1037
4-6
if-else
選擇結構僅提供一種可選執行路徑。
4-7
_比較_運算符可用來確定兩個值之間是否存在特定關系。
4-8
Python提供了一種特殊的選擇結構,稱為__嵌套if-else___
語句,這使得嵌套選擇結構的邏輯更易於編寫。
4-9
_reverse()_方法用於反轉列表中元素的順序。
4-10
_Matplotlib_軟件包是一個庫,Python中使用該庫可用來創建二維圖表和圖形
程序填空題
5-1
函數repeat(ls)判定列表ls中是否包含重復元素,如果包含返回True,否則返回False。每一個列表中只要有一個元素出現兩次,那么該列表即被判定為包含重復元素。
然后使用該函數對n行字符串進行處理。最后統計包含重復元素的行數與不包含重復元素的行數。
輸入格式:
輸入n,代表接下來要輸入n行字符串。 然后輸入n行字符串,字符串之間的元素以空格間隔。
輸出格式:
True=包含重復元素的行數, False=不包含重復元素的行數。
其中逗號后面有空格。
輸入樣例:
5
1 2 3 4 5
1 3 2 5 4
1 2 3 6 1
1 2 3 2 1
1 1 1 1 1
輸出樣例:
True=3, False=2
def repeat(ls):
s = set(ls)
if len(ls) == len(s): # ________
return False
else:
return True
n = int(input())
countT = countF = 0
for i in range(n):
if repeat(input().split()):# ________
countT += 1
else:
countF += 1
print("True=%d, False=%d" % (countT, countF))# ________
5-3
本題用遞歸函數實現對列表中元素的折半查找。顯示出每一步查找中,查找元素存在列表中的左邊或右邊列表中。列表切片時列表的下標必須有起始位置數。
def twosplit(sourceDate, findData):
sp = int(len(sourceDate) / 2) # int()
if sourceDate[sp] == findData:# if ___ == findData:
print("find data:", sourceDate[sp])# print("find data:", ________)
elif findData in sourceDate[:sp]:# elif findData in _______:
print("data in left", sourceDate[:sp])# print("data in left", ______)
twosplit(sourceDate[:sp], findData)# twosplit(______, ____________)
elif findData in sourceDate[sp:]:# elif findData in ________:
print("data in right", sourceDate[sp:])# print("data in right", ______)
twosplit(sourceDate[sp:], findData)# twosplit(__________, findData)
else:
print("can't find data", findData)# _______
data = [1, 2, 3, 4, 5, 6, 7, 8, 17, 26, 15, 14, 13, 12, 11, ]
find = int(input())
twosplit(data, find)
5-4
一個整數,它加上100后是一個完全平方數,再加上168又是一個完全平方數,請問該數是多少?
from math import sqrt
x = 0
while True:
a = x + 100
b = x + 268
a = sqrt(a)
b = sqrt(b)
if int(a) * int(a) == x + 100 and int(b) * int(b) == x + 268:# if __:
print(x)
break
x += 1
函數題
6-1 人民幣美元雙向兌換 (6分)
本題要求實現一個人民幣與美元的雙向兌換函數change(money),可實現1美元=6.709人民幣的雙向兌換。輸出兌換的結果保留2位小數。
函數接口定義:
在這里描述函數接口。例如:
change( money )
其中 money都是用戶傳入的參數,表示待兌換的錢數。
裁判測試程序樣例:
/* 請在這里填寫答案 */
x = input()
change(x)
輸入樣例1:
在這里給出一組輸入。例如:
$1
輸出樣例1:
在這里給出相應的輸出。例如:
1美元 = 6.71人民幣
輸入樣例2:
在這里給出一組輸入。例如:
¥1
輸出樣例2:
在這里給出相應的輸出。例如:
1人民幣 = 0.15美元
code :
def change(x):
k = float(x[1::])
a = list(x)
if a[0] == '$':
print('{0}美元 = {1:.2f}人民幣'.format(int(k),6.709*k))
elif a[0] == '¥':
print('{0}人民幣 = {1:.2f}美元'.format(int(k),k/6.709))
6-2 可變參數傳遞 (6分)
本題要求實現一個函數,可輸出姓名、出生日期、性別、國籍和電話,並根據出生日期算出歲數(需要判斷是否足歲)。函數可以對輸入中的錯誤信息進行捕獲。
函數接口定義:
def student(name,*birth,**information)
name參數是姓名,birth參數是出生年、月、日,information參數是性別、國籍和電話。
裁判測試程序樣例:
name = input()
birth = input()
student(name,birth,sex='Female', nation='China', phone='123456789')
輸入樣例0:
在這里給出一組輸入。例如:
zhangsan
1999 2 3
輸出樣例0:
在這里給出一組輸出。例如:
name:zhangsan
birth:1999-2-3
age is 20
sex:Female
nation:China
phone:123456789
輸入樣例1:
在這里給出一組輸入。例如:
zhangsan
1999-2-3
輸出樣例1:
在這里給出一組輸出。例如:
name:zhangsan
The interval in the input 'birth' is a space
code :
from datetime import date
def student(name, *birth, **information):
string = birth[0] # 將出生日期轉化為字符串
if ' ' not in string: # 這里僅判斷出生日期不以空格為間隔的情況
print('name:{}'.format(name))
print("The interval in the input 'birth' is a space")
else:
ls = string.split() # 將字符串轉化為列表
year = ls[0] # 切片儲存
month = ls[1]
day = ls[2]
today = date.today() # 獲取今天的日期
age = today.year - int(year) - ((today.month, today.day) < (int(month), int(day)))
print('name:{}'.format(name))
print('birth:{}-{}-{}'.format(year, month, day))
print('age is', age-1)
for k, v in information.items():
print('{}:{}'.format(k, v))
6-3 Largest Factor (3分)
Write a function that takes an integer n that is greater than 1 and returns the largest integer that is smaller than n and evenly divides n
def largest_factor(n):
"""Return the largest factor of n that is smaller than n.
>>> largest_factor(15) # factors are 1, 3, 5
5
>>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
40
>>> largest_factor(13) # factor is 1 since 13 is prime
1
"""
"*** YOUR CODE HERE ***"
Hint: To check if b evenly divides a, you can use the expression a % b == 0, which can be read as, "the remainder of dividing a by b is 0."
code :
def largest_factor(n):
for i in range(1, n):
if n % i == 0:
ans = i
return ans
編程題
7-1 冠軍魔術 (10分)
2018年FISM(世界魔術大會)近景總冠軍簡綸廷的表演中有一個情節:以桌面上一根帶子為界,當他將紙牌從帶子的一邊推到另一邊時,紙牌會變成硬幣;把硬幣推回另一邊會變成紙牌。
這里我們假設紙牌會變成等量的硬幣,而硬幣變成紙牌時,紙牌的數量會加倍。那么給定紙牌的初始數量,當他來回推了 N 次(來/回各算一次)后,手里拿的是紙牌還是硬幣?數量是多少?
輸入格式:
輸入在一行里給出兩個正整數,分別是紙牌的初始數量和魔術師推送的次數。這里假設初始狀態下魔術師手里全是紙牌。
輸出格式:
如果最后魔術師手里是紙牌,輸出 0 和紙牌數量;如果是硬幣,則輸出 1 和硬幣數量。數字間須有 1 個空格。題目保證結果數值不超出整型范圍(即 2^31−1)。
輸入樣例 1:
3 7
輸出樣例 1:
1 24
輸入樣例 2:
8 4
輸出樣例 2:
0 32
code :
a,b = input().split(" ")
b = int(b)
a = int(a)
for i in range(1,b+1):
if i % 2 == 0:
a*=2
if b % 2 ==0 :
print("0 ",end="")
print(a)
if b % 2 !=0 :
print("1 ",end="")
print(a)
7-2 冰島家譜 (10分)
冰島是作為一個人口稀少的國家,人群之間具有復雜的血緣關系,為了避免不必要的意外,他們的手機上都安裝了一款可以隨時查詢兩個人之間是否有血緣關系的軟件。現在你的任務就是實現這樣一個功能,接收血緣關系的登記信息,並在我們查詢時給出兩個人是否具有血緣關系。
血緣關系具有自反性、傳遞性。
輸入格式:
一行整數n,以下n行,每行3個正整數q、a、b
若q為1,則登記a與b具有血緣關系
若q為2,則查詢a與b的血緣關系,若有,輸出一行YES;若無,輸出一行NO。
輸出格式:
對於每個q=2,輸出一行YES或NO。
輸入樣例:
5
1 1 2
1 3 4
2 1 3
1 2 3
2 1 4
輸出樣例:
NO
YES
數據范圍:
對於20%的數據,n<=1000
對於100%的數據,n<=10^7 ,1<=a,b<=n
code :
N = 100005
p = [0] * N
def find(x):
if (p[x] != x):
p[x] = find(p[x])
return p[x]
m = int(input())
for i in range(1, 100005):
p[i] = i
while m:
row = input().split()
if row[0] == '1':
p[find(int(row[1]))] = find(int(row[2]))
else:
if (find(int(row[1])) == find(int(row[2]))):
print('YES')
else:
print('NO')
m -= 1