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