本篇整理了上一篇Python算法题的答案,因为后面自己接触到了lambda,reduce,filter等函数,所以部分题目写了两种或者多种实现方式。
1 # ----------------公司一---------------- 2 #第一道题: 3 str001 = "my love is you do you konw it ? do you love me ?" 4 list001 = str001.split(‘ ‘) 5 print(list001) 6 print(str001.count(‘ ‘)) 7 print("单词的总数为%s" % (len(list001))) #14 8 print("空格的总数为%s" % str001.count(‘ ‘)) #13 9 print("you的总数为%s" % (list001.count(‘you‘))) #3 10 # 解释一下整个程序的过程? 11 # 以空格为分隔符,将字符串转化成列表,分别统计单词、空格、you的数量。 12 13 #第二道题:一个数的阶层运算,求结果 14 def func001(a): 15 if a == 1: 16 return 1 17 else: 18 return a*(func001(a-1)) 19 20 result = func001(5) 21 print(result) #120 22 23 #第三道题目:实现一个数字的斐波那切数列 24 # 8 的菲波那切数列数列为: [1,1,2,3,5,8,13,21] 25 def func001(a): 26 list001 = [] 27 j = 1 28 for i in range(1,a+1): 29 if i == 1 or i == 2: 30 j == 1 31 else: 32 j = list001[i-2] + list001[i-3] 33 list001.append(j) 34 print("%s的菲波那切数列是%s" %(a,list001)) 35 func001(8) 36 37 #第四道题(机试题):将一个列表的负数给删掉,然后再返回最终的列表 38 #错误代码 39 """ 40 def listHandle(a): 41 for i in a: 42 if i < 0: 43 a.remove(i) 44 return a 45 list001 = [1,3,-3,5,-4,-6,10] 46 print(listHandle(list001)) 47 """ 48 #正确代码 49 def listHandle(a): 50 i = 0 51 b = a.copy() # 或者b = a[:] ; 或者 b = copy.copy(a) 52 while i < len(a): 53 if a[i] < 0: 54 a.pop(i) # 或者a.remove(a[i]) 55 else: 56 i +=1 #正数才需要加1,负数被删除导致后面的数顶替上来,索引不变,继续原索引判断 57 print("列表%s剔除掉负数后的新列表为%s" %(b,a)) 58 list001 = [1,3,-3,5,-4,-6,10] 59 listHandle(list001) 60 61 # ----------------公司二---------------- 62 """ 63 机试题1: 64 读取某个json文件,取出某个key下面所有的值(列表嵌套字典) 65 再拿到嵌套字典里面的value值,然后以第一个value值为key,第二个value值为value追加到新的字典内 66 新字典格式{"fe5f5a07539c431181fc78220713aebein01":"zyy1","73ea2bf70c73497f89ee0ad4ee008aa2in01","zyy2"} 67 json文件内容: 68 { 69 "configuration_id": "cf49bbd7d2384878bc3808733c9e9d8bpr01", 70 "configuration_name": "paramsGroup-bcf9", 71 "apply_results": [ 72 { 73 "instance_id": "fe5f5a07539c431181fc78220713aebein01", 74 "instance_name": "zyy1" 75 }, 76 { 77 "instance_id": "73ea2bf70c73497f89ee0ad4ee008aa2in01", 78 "instance_name": "zyy2" 79 } 80 ], 81 "success": false 82 } 83 84 """ 85 86 import json 87 88 # 方式二:多行实现(循环) 89 with open(‘transfer.json‘, ‘r‘) as fp: 90 content = fp.read() 91 theDict = json.loads(content) # json字符串转字典 92 theList = theDict.get("apply_results") # 获取字典内的列表 93 List01 = [] 94 for i in theList: 95 List01.append(i.values()) # values():将字典的value追加到列表内并返回 96 print(List01) 97 theDict = dict(List01) # 列表转换成字典 98 print("the final dict is ", theDict) 99 100 # 方式二:单行实现 101 with open(‘transfer.json‘, ‘r‘) as fp: 102 theList = json.loads(fp.read()).get("apply_results") 103 the_dict = dict(map(lambda x: x.values(), theList)) 104 print("the final dict is ", the_dict) 105 106 107 """ 108 机试题2: 109 测试两个接口,一个post,一个为get 110 用Python脚本写出断言httpCode ,msg 等信息的相关代码 111 """ 112 import unittest 113 import json 114 import requests 115 class InterfaceTest(unittest.TestCase): 116 def setUp(self): 117 pass 118 119 def test_get(self,url,param): 120 try: 121 response = requests.get(url,param) 122 response = json.dumps(response) 123 #断言 124 self.assertEqual(response[‘status_code‘],200,msg=‘status_code不等于200‘) 125 self.assertEqual(response[‘msg‘],‘登录成功‘,msg=‘登录失败‘) 126 except AssertionError as e: 127 print(‘%s‘ %e) 128 129 def test_post(self,url,param): 130 header = {‘Content-Type‘:‘application/json‘} 131 try: 132 response = requests.post(url,param,headers=header) 133 response = response.dumps(response) 134 #断言 135 self.assertEqual(response[‘status_code‘],200,msg=‘status_code不等于200‘) 136 self.assertEqual(response[‘msg‘],‘登录成功‘,msg=‘登录失败‘) 137 except AssertionError as e: 138 print(‘%s‘ %e) 139 140 def tearDown(self): 141 pass 142 143 if __name__ == "__main__": 144 unittest.main() 145 146 # ----------------公司三---------------- 147 """ 148 面试时间:2019/11/26 149 面试题1:1加到N的阶层之和,比如N=4, result = (1! + 2! + 3! + 4!) 150 151 """ 152 153 # 方式一:借助reduce、lambda、append函数 154 the_list = [] 155 def countResult(a): 156 for i in range(1, a + 1): 157 result = reduce(lambda x, y: x * y, range(1, i + 1)) 158 the_list.append(result) 159 print(the_list) 160 return sum(the_list) 161 print(countResult(5)) 162 163 # 方式二:借助reduce、lambda函数 164 result = 0 165 temp = 0 166 def countResult(a): 167 for i in range(1, a + 1): 168 global result 169 global temp 170 temp = reduce(lambda x, y: x * y, range(1, i + 1)) 171 result += temp 172 return result 173 print(countResult(5)) 174 175 # 方式三:传统循环 176 result = 0 177 temp = 1 178 def countResult(a): 179 for i in range(1, a + 1): 180 global result 181 global temp 182 for j in range(1, i + 1): 183 temp = temp * j 184 result += temp 185 temp = 1 186 return result 187 188 print(countResult(5)) 189 190 191 # ----------------公司四---------------- 192 """ 193 面试题1:实现一个数字的反转,比如输入123,输出321 194 """ 195 196 # 方式一: 197 a = input("请输入数字:") 198 a = a[::-1] 199 print(a) 200 201 # 方式二: 202 a = 12345 203 theList = [] 204 for i in str(a): 205 theList.append(i) 206 theList.reverse() 207 a = "".join(theList) 208 a = int(a) 209 print(a) 210 211 212 """ 213 面试题2:用awk命令将日志里面的时分秒,日期取出来 214 日志文件内容: 215 181014 21:48:01 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql 2019-12-13 216 181014 21:48:02 InnoDB: Initializing buffer pool, size = 8.0M 2019-12-13 217 181014 21:48:02 InnoDB: Completed initialization of buffer pool 2019-12-13 218 """ 219 # 这道题当时没做对,想到取时间/日期,第一反应想到的是用正则取,其实应该考虑通过列将它们取出来 220 # awk ‘{print $2,$NF}‘ log_test.log 221 222 # ----------------公司五---------------- 223 """ 224 写一个快排的算法程序 225 """ 226 227 # 方式一: 借助lambda实现 228 the_list = [2, 1, 4, 5, 10, 21, 34, 6] 229 quick_sort = lambda tempList: tempList if len(tempList) <= 1 else quick_sort([item for item in tempList[1:] if item <= tempList[0]]) + [tempList[0]] + quick_sort([item for item in tempList[1:] if item > tempList[0]]) 230 231 quick_sorted_list = quick_sort(the_list) 232 print("列表:{0}快速排序后的新列表为:{1}".format(the_list,quick_sorted_list)) 233 234 # 方式二:函数式编程+循环 235 print(‘-----------------------------‘) 236 237 def quickSort(tempList): 238 if len(tempList) <= 1: 239 return tempList 240 midNum = tempList[len(tempList) // 2] 241 tempList.remove(midNum) 242 leftList, rightList = [], [] 243 for i in tempList: 244 if i < midNum: 245 leftList.append(i) 246 else: 247 rightList.append(i) 248 return quickSort(leftList) + [midNum] + quickSort(rightList) 249 250 251 quick_sorted_list = quickSort(the_list) 252 print("列表:{0}快速排序后的新列表为:{1}".format(the_list,quick_sorted_list)) 253 254 255 # ----------------公司六---------------- 256 """ 257 写一个冒泡排序的算法程序 258 """ 259 the_list = [123,22,33,23,3,5,778,12] 260 261 #冒泡排序(方式一:for循环) 262 requirement = "冒泡排序" 263 the_len = len(the_list) 264 for i in range(0,the_len-1): 265 for j in range(0,the_len-1-i): 266 if the_list[j] > the_list[j+1]: #从小到大排序用大于号,从大到小排序用小于号 267 the_list[j],the_list[j+1] = the_list[j+1],the_list[j] 268 269 print(requirement + "后的列表是:"+ str(the_list)) 270 print(requirement + "后的列表是:%s" %(str(the_list))) 271 print(requirement + "后的列表是:",the_list) 272 273 print("while循环实现顺子判断---------------") 274 275 """ 276 冒泡排序(方式二:while循环) 277 冒泡排序跟九九乘法表很像 278 """ 279 the_list = [123,22,33,23,3,5,778,12] 280 list_002 = [3,2,1,4,5,7,6] 281 282 def order_list(a): 283 x = 0 284 y = 0 285 while x < len(a): 286 while y < (len(a) - x -1): 287 if a[y] > a[y+1]: 288 a[y],a[y+1] = a[y+1],a[y] 289 y +=1 290 x+=1 291 y=0 292 order_list(the_list) 293 294 # ----------------公司七---------------- 295 """ 296 递归实现统计列表1~9999中3出现的次数 297 """ 298 299 #方式一:循环+递归实现 300 print(‘-----------------------------‘) 301 a = list(map(lambda x: str(x),list(range(1,10000)))) 302 count = 0 303 def theCount(c): 304 for i in c: 305 if len(i) == 1: 306 if i == ‘3‘: 307 global count 308 count +=1 309 else: 310 continue 311 else: 312 theCount(i) 313 theCount(a) 314 print("列表[1~9999]中3出现的总次数为:{}".format(count)) 315 316 317 #方式二:嵌套循环实现 318 print(‘-----------------------------‘) 319 count = 0 320 for i in a: 321 for j in str(i): 322 if j == ‘3‘: 323 count +=1 324 print("列表[1~9999]中3出现的总次数为:{}".format(count)) 325 326 327 """ 328 统计列表1~9999中包含3的元素的总个数 329 """ 330 331 #方式一:结合fitler,lambda,re.match()函数实现 332 print(‘-----------------------------‘) 333 import re 334 335 theList = list(filter(lambda x: re.match(‘(.*?)3(.*?)‘,str(x)) ,a)) 336 print("列表[1~9999]中包含3的元素总个数为:{}".format(len(theList))) 337 print(theList) 338 339 340 #方式二:循环+re模块实现 341 print(‘-----------------------------‘) 342 count = 0 343 for i in a: 344 if re.match(‘(.*?)3(.*?)‘,i): 345 count += 1 346 else: 347 continue 348 349 print("列表[1~9999]中包含3的元素总个数为:{}".format(count)) 350 351 #方式三:列表推导式 352 print(‘-----------------------------‘) 353 theList = [ x for x in a if re.match(‘(.*?)3(.*?)‘,x)] 354 print("列表[1~9999]中包含3的元素总个数为:{}".format(len(theList)))
原文:https://www.cnblogs.com/Sean-Pan/p/12163410.html