python編程題集錦_軟件測試工程師


# 1.獲取1-100之間的素數(大於1的並不能被1和本身整除的數叫素數,也叫質數)
list = [] #構造1-100的數字列表
for i in range(1,101): list.append(i) print(list) # 判斷素數
for i in range(1,101): for j in range(2,i): # 遍歷2開始到i-1之間的數字j,如果i能被數字j整數,則i不是素數
        if i%j==0: list.remove(i) # 移除非素數
            break
print(list) #打印結果

''' 2.給定一個整數 num,從 1 到 num 按照下面的規則返回每個數運算結果 如果num被 3 整除,返回 'Fizz'。 如果num被 5 整除,返回 'Buzz'。 如果num能同時被 3 和 5 整除,返回 'FizzBuzz'。 如果num既不能被 3 也不能被 5 整除,返回這個數字的字符串格式 '''
# 定義函數
def f(num): dict = {} for i in range(1,num+1): if i%3==0 and i%5!=0: dict[i]='Fizz'
        elif i%3!=0 and i%5==0: dict[i]= 'Buzz'
        elif i%3==0 and i%5==0: dict[i]= 'FizzBuzz'
        else: dict[i]= str(i) return dict # 調用函數
print(f(100)) # 3.選擇排序(升序):關注最小元素
''' 選擇排序: 原理: 1.第一個元素看成是最小值,然后和下一個值比較,誰小,誰就放到最左邊。這樣比一圈。 2.然后在剩下元素里面繼續這樣比較,得到第二個最小值且放到最左邊(第二個位置) 實現: 1.雙層for循環,外循環需要循環n-1次。 2.第一次外循環,內循環需要循環n-1次,內循環次數是逐減的。 '''
# 定義函數
def select_sort(list): for i in range(list.__len__()-1):  # 外循環4次
        for j in range(i+1, list.__len__()):  # 一開始,內循環4次
            if list[i] > list[j]: # i = 0 # i=1
                # j = 1,2,3,4 # j=2,3,4
                list[i], list[j] = list[j], list[i]  # 交換位置
                pass
    return list # 調用函數
list = [1, 5, 3, 18, 8] print( select_sort(list=list) ) # 4.冒泡排序(升序):關注最大元素
''' 冒泡排序: 原理: 1.相鄰元素比較,誰大,誰放右邊,這樣比一圈,最右邊的值就是最大值。 2.剩下元素里面,繼續這樣比,第二個最大值放到最右邊(倒數第二位) 實現: 1.雙層for循環,外循環需要循環n-1次。 2.第一次外循環,內循環需要循環n-1次,內循環次數是逐減的。 '''
# 定義函數
def bubble_sort(list): for i in range(list.__len__()-1):  # 外循環4次
        for j in range(list.__len__()-1-i):  # 一開始,內循環4次
            if list[j] > list[j+1]: # 相鄰元素比較,如果左邊的大,則互換位置,保證右邊的值要大
                list[j], list[j+1] = list[j+1], list[j] return list # 調用函數
list = [5,4,1,3] print( bubble_sort(list=list) ) # 5.在有序數組中采用“二分法”查找某元素的位置。 # (系統提供了list.index()方法來查找元素的索引)
def halfSearch(arr,key): """arr為傳入的數組,key為需要查找的元素 """ min_index = 0 max_index = len(arr) if key in arr: while True: mid_index = int((min_index + max_index)/2) #中位數
            if key >arr[mid_index]: # 如果查找的數在中位數的右邊
                min_index = mid_index + 1
            elif key <arr[mid_index]: # 如果查找的數在中位數的左邊
                max_index = mid_index - 1
            else: # 否則key = arr[mid_index]
                return mid_index else: return -1; # 自定義-1代表不存在該元素

# 調用函數
arr = [1,4,6,9,14] key = 9
print(f'元素{key}的索引:', halfSearch(arr,key)) # 6.定義遞歸函數求n的階乘之和。比如當n=4, 求 4!+3!+2!+1!之和 #遞歸求階乘
def f(x): if x == 1: return 1
    return f(x-1)*x #遞歸求和
def fn(x): if x==1: return 1
    # def f(x): # 在函數體定義一個函數
    # if x == 1:
    # return 1
    # return f(x - 1) * x
    return fn(x-1)+f(x) #調用函數
print(fn(3)) ''' 7.給定一個整型數組: 返回最大前后差(數組中位置靠后的數 - 數組中位置靠前的數) 比如對於數組[3,6,9,7,10,1,2,5] 10-3是一個前后差,為7 5-1是一個前后差,為4 而10-1則不是一個前后差,因為10的位置在1的前面。 故本數組最大前后差為7。 如果本數組為單調遞減數組,則返回0。 數組長度介於1-100000之間。 程序的運行時間應該盡可能短。 '''
# 定義函數
def max_diff(list): list2 = [] # 封裝差值
    # 雙層for循環,獲取當前元素和右邊所有元素的差值
    for i in range( list.__len__() ): for j in range(i+1, list.__len__()): val = list[j] - list[i] # [3,6,9,7,10,1,2,5]
            list2.append(val) # 收集差值

    # 判斷差值是否全為負數
    count = 0 # 統計差值為負數的數量
    for e in list2: if e < 0: count = count + 1
    if count == list2.__len__(): return 0 # 為單調遞減列表
    else: list2.sort() # 排序:默認為升序
        return list2[list2.__len__()-1] # 最后一個元素是最大的 # 調用函數
list = [3,6,9,7,10,1,2,5] # len = 8
print( max_diff(list) ) # 7
''' 8.一個班級有N名同學,每個同學有編號id、身高height、體重weight。 要求同學們按身高從低到高進行排序,並計算所有同學的體重的和 要求: 1、閉卷,30 分鍾 2、使用熟悉的編程語言實現題目要求,定義一個函數、輸入一個數組(列表), 打印出根據身高從低到高排序后的結果,返回體重的和,最低要求實現體重的和。 數組格式為: [ { "id": 1, "height": 175, "weight": 60 }, { "id": 2, "height": 160, "weight": 54 }, { "id": 3, "height": 181, "weight": 64 }, ] 舉例: 上述數組排序后的結果為: [{"id": 2, "height": 160, "weight": 54}, {"id": 1, "height": 175, "weight": 60}, {"id": 3, "height": 181, "weight": 64}, ] 體重和為178 '''
# 定義函數
def sortKeys(students): # 遍歷到列表元素(字典),調用key方法,傳給student變量名,返回身高值,居於身高排序
    students_new = sorted(students, key=lambda student: student["height"] ) # 獲取體重之和
    sum = 0 for student in students: sum = sum + student["weight"] return students_new, sum  # 返回元組

# 調用函數
students = [ {"id": 1, "height": 175, "weight": 60 }, {"id": 2, "height": 160, "weight": 54 }, {"id": 3, "height": 181, "weight": 64 }, ] tup = sortKeys(students) print(f'按身高升序:{tup[0]},\n體重之和:{tup[1]}' ) # 9.定義一個數組,只包含正整數, 返回該數組中重復次數最多的前N個數字,返回結果按重復次數,從多到少降序排列。
list = [1,2,3,22,1,2,3,1,1,1,2,22,22,22] # 定義函數
def countN(list, N): dict = {} # 用於存放“數字及出現次數”的鍵值對
    list2 = [] # 用於存放重復次數比較多的數字
    for i in list: dict[i] = list.count(i)  # 統計當前元素的個數,並以鍵值對形式存放到字典
    print(dict.items()) # dict.items()返回鍵值元組的列表,x[1]根據值value排序,x[0]根據鍵key排序
    new_list = sorted(dict.items(),key=lambda x:x[1],reverse=True) # 按重復次數,倒序
    for a in new_list: list2.append(a[0]) # 排序后,獲取鍵值元組的鍵(數字)
    print(list2[0:N]) # 切片,截取重復次數最多的前N個數字 # 調用函數
countN(list, 3) # 10.定義一個方法,判斷字符串中的括號數量是否匹配。比如:(hello(welcome(come to)))
def matchs(str): #記錄左右括號數量的變量
    left=0 right=0 #遍歷字符串中的字符
    for i in str: if i=="(": left=left+1
        elif i==")": right=right+1
    #數量匹配則返回True,否則False
    return left==right #調用函數
str = '(hello(welcome(come to)))'
print(matchs(str))

 

''' 11.
編寫一個函數來查找字符串數組中的max same string. 如果不存在same string,返回空字符串"". 【示例】 示例1: 輸入:strs = ["flower", "flow", "flight"] 輸出:"fl" 示例2: 輸入:strs = ["dog", "racecar", "car"] 輸出:"" 解釋:輸入不存在公共前綴。
''' # 定義函數 def max_same_str(strs): same_strs = [] # 用於保存列表元素中相同的子串 first = strs[0] # 獲取列表第一個元素 # 雙層for循環,遍歷列表第一個元素的所有子串 for i in range(0, len(first)+1): for j in range(i+1, len(first)+1): count = 0 # 記錄子串在列表中出現的次數 for str in strs: # 遍歷列表元素 if str.__contains__( first[i:j] ): # 判斷第一個列表元素的子串是否在列表的所有元素中 count = count + 1 # 記錄第一個列表元素的子串在列表中出現的次數 if count == len(strs): # 當子串在列表中出現的次數和列表元素數量一致時,保存當前子串 same_strs.append( first[i:j] ) print(same_strs) # 打印列表元素中相同的子串 if same_strs == []: #如果不存在相同的子串,返回空字符串"". return '' else: same_strs.sort(key=len,reverse=True ) # 按照元素的長度,倒序 return same_strs[0] # 第一個元素則是長度最大的 # 調用函數 strs = ["flower","flow","flight"] print( max_same_str(strs) )

 

''' 12、請實現一個函數,將一個字符串中的空格替換成“%20”。例如: 當字符串為We Are Happy.則經過替換之后的字符串為We%20Are%20Happy (實現語言不限,不能使用replace方法) '''
# 定義函數
def space_replace(str): str_list = str.split(' ') # 按照空格切割,返回列表
    str_new = '%20'.join(str_list) # 列表元素之間使用%20連接,返回字符串
    return str_new # 調用函數
str = 'We Are Happy'
print( space_replace(str) )

 

''' 13、聖誕節到了,公司舉行交換禮物活動,參加的員工每人准備一個禮物。 交換完成后,自己的禮物會隨機給到另一個人,自己也能隨機獲得一個其他人准備的禮物。不要求A拿了B的禮物, B就一定要拿A的,只要自己不拿自己的即可。為公平起見,請你寫一個隨機程序來決定禮物何分配。 '''
import random # 定義函數
def switch_gift(gifts): values = list(gifts.values())     # 將所有物品集中放入一個列表
    gifts_new = {}      # 創建一個空字典,將交換成功的數據存入字典
    print("交換中......") count = 0 # 記錄交換的次數
    flag = 0 # 記錄是否其他人交叉分到禮物,而最后一個人分到自己的禮物
    for key in gifts.keys():     # 將人都遍歷出來
        while True: value = random.choice(values)   # 隨機在列表中抽取一個數據
            if gifts[key] != value:     # 如果從原字典對應的value不等於隨機取出來的數,則存入gifts_new
                gifts_new[key] = value values.remove(value) # 將取出來的數據從列表values中剔除
                count = count + 1 # 交換次數加1
                print(count) break
            if count==3 and gifts[key]==value: # 第四次無效交換時,count沒有被加1
                flag = 1 # 其他人交叉分到禮物,而最后一個人分到自己的禮物
                break
    if flag == 0: # 返回最新字典
        return gifts_new elif flag == 1: return switch_gift(gifts) # 重新交換禮物(遞歸調用函數)

# 調用函數
gifts = {'a':'apple','b':'bed','c':'car','d':'dog'} # 將每個人擁有自己的物品變為一個字典
gifts_new = switch_gift(gifts) # 遍歷字典
for k, v in gifts_new .items(): print( f'{k}分到{v}' )

 

14、請用熟悉的代碼編寫:從名為"words.xlsx""sheet1"中獲取單詞,調用接口, 將返回值phoneticEn,explanations, nounPlurals 寫入到文件"words.xlsx"中; url='https://test.gu.cn/api/mini/search/wordv2' data={"txt":"hello","uuid":"40d91","isFirst":1} 請求方式:post Sheet1 內容: |--------------------------------------------------------------------------|
|單詞   |phoneticEn              |  explanations             |nounPlurals   |
|------|------------------------|---------------------------|--------------|
|hello |  [hə'ləu; he-] | "meaning":"喂; 哈羅", |hellos |
|      |                        |  "pos":"int"              |              |
|--------------------------------------------------------------------------|
|pen   |                        |                            |             |
|--------------------------------------------------------------------------|
|pencil|                        |                            |             |
|--------------------------------------------------------------------------|
|ruler |                        |                            |             |
|--------------------------------------------------------------------------|
|eraser|                        |                            |             |
|--------------------------------------------------------------------------|     
|…     |                        |                            |             |
|--------------------------------------------------------------------------|
返回示例: { "errcode":0, "errmsg":"ok", "data":{ "code": 200, "done":true, "message":"success", "nlpResponse":{ "intent":{ "code":1000633, "parameters":{ "content":"hello", "result":{ "dict":"en_word",pe "dictTy":"tuling", "info":{ "adjective":"", "comparativeDegree":"", "examples":{ { "cn":"喂?我是托尼。", "en":"Hello? Tony here." } }, "explanations":{ { "meaning":"喂;哈羅", "pos":"int" } }, "isCollect":false, "nounPlurals":"hellos", "pastParticiple":"helloed", "phoneticEn":" [he' leu ; he-]", "phoneticUs":" [he' lo ; he-]", "presentParticiple":"helloing", "preterit":"helloed", "proto":"", "superlativeDegree":"", "thirdSingular":"", "verb":"", "word":"hello", } } } } } } } 答案: #!/usr/bin/env python from xlrd import open_workbook # 安裝讀取excel的模塊:pip install xlrd==1.2.0; from xlutils.copy import copy # 安裝excel工具模塊:pip install xlutils; import requests,pytest def get_data():# 獲取excle參數化文件的參數 r_xls = open_workbook('words.xlsx') # 讀取excel文件 sheet = r_xls.sheet_by_index(0) # 返回列表:['hello', 'pen', 'pencil', 'ruler', 'eraser'] col = sheet.col_values(0,start_rowx=1) # 形成二維列表 list = [] for i in col: list.append([i]) return col # print(col) class TestWords: def setup(self): # 環境預設 self.session = requests.session() self.ip = 'https://test.gu.cn' def teardown(self): # 環境恢復 self.session.close() @pytest.mark.parametrize('txt',get_data()) def test_query(self,txt): # 測試用例 url = '/api/mini/search/wordv2' data = {"txt": txt, "uuid": "40d91", "isFirst": 1} resp = self.session.post(url=self.ip + url, json=data).json() # 轉為字典 # 提取phoneticEn、explanations、nounPlurals。 # 轉為字典通過key獲取value 或 高仿邊界提取器 phoneticEn = resp['data']['nlpResponse']['intent']['parameters']['result']['info']['phoneticEn'] explanations=str(resp['data']['nlpResponse']['intent']['parameters']['result']['info']['explanations'][0])[1:-1] nounPlurals = resp['data']['nlpResponse']['intent']['parameters']['result']['info']['nounPlurals'] # 往excel文件寫入內容 r_xls = open_workbook('words.xlsx') # 讀取excel文件 # rows = r_xls.sheets()[0].nrows # 獲取已有的行數 rows = (get_data().index(txt)) + 1 # 獲取當前操作的行索引 excel = copy(r_xls) # 將xlrd可讀的對象轉化為xlwt可寫的對象 worksheet = excel.get_sheet(0) # 獲取要操作的sheet # 針對指定行,填入列信息 worksheet.write(rows, 1, phoneticEn) # 括號內分別為行數、列數(從0開始算)、內容 worksheet.write(rows, 2, explanations) worksheet.write(rows, 3, nounPlurals) excel.save("words.xlsx") # 保存並覆蓋文件 # 主程序 if __name__ == '__main__': pytest.main(['-s','./test_words.py'])

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM