本篇整理了上一篇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)))