Python逻辑面试题
1 # *****************************列表操作***************************** 2 # names = ["Lihua","Rain","Jack","Xiuxiu","Peiqi","Black"] 3 # names.append('Blue') 4 # names[3]='修修' 5 # names.insert(2,["oldboy","oldgirl"]) 6 # names2 = [1,2,3,4,2,5,6,2,] 7 # # new_names = names+names2 8 # names.extend(names2) 9 # print(names) 10 # print(names[4:8]) 11 12 # *****************************取出names列表中索引2-10的元素,步长为2。***************************** 13 # print(names[2:11:2]) 14 # print(names[-3:]) 15 16 # *****************************循环names列表,打印每个元素的索引值和元素。***************************** 17 # for i in names: 18 # if names.index(i) % 2 == 0: 19 # res = names.index(i) 20 # names[res] = -1 21 # print(names.index(2,names.index(2)+1)) 22 23 # *****************************购物车***************************** 24 # products = [["iphone",6888],["MacPro",14800],["小米6",2499],["Coffee",31],["Book",60],["Nike",699]] 25 # print('---------商品列表-----------') 26 # for index,i in enumerate(products): 27 # print("%s %s %s" % (index, i[0], i[1])) 28 # !-*- coding:utf-8 -*- 29 # products = [["iphone",6888],["MacPro",14800],["小米6",2499],["Coffee",31],["Book",60],["Nike",699]] 30 # shop_car = [] # 用户购物车 31 # shop_cost = 0 # 用户花费的金额 32 # exit_log = False # 标志位,默认设为False,退出 33 # while not exit_log: 34 # print("------ 商品列表 ------") 35 # for index,i in enumerate(products): 36 # print("%s %s %s"%(index,i[0],i[1])) 37 # user_choice = input("\n输入你想购买的产品序号(按“q”退出):") 38 # if user_choice.isdigit(): 39 # # 判断用户输入的是否是数字 40 # user_choice = int(user_choice) #强制转换为数字 41 # # if user_choice >= 0 and user_choice < len(products): 42 # if 0 <= user_choice < len(products): 43 # # 判断用户购买的商品是否在商品列表中 44 # shop_car.append(products[user_choice]) # 加入购物车 45 # shop_cost += products[user_choice][1] # 计算费用 46 # print("\n %s 已经加入你的购物车\n"%products[user_choice]) 47 # else: 48 # print("抱歉,此商品不存在\n") 49 # elif user_choice == "q": 50 # # 用户选择退出 51 # if len(shop_car)>0: 52 # # 判断用户是否购买了商品 53 # print("\n------ 你的购物车 ------") 54 # for index,i in enumerate(shop_car): 55 # # index和i为临时变量,与前一个for循环里index和i作用的列表不同,故可重用 56 # print("%s %s"%(i[0],i[1])) 57 # print("\n你此次购物的花费合计是:%s元\n"%shop_cost) 58 # exit_log = True # 退出购物 59 # else: 60 # exit_log = True # 未购买商品,不打印购物车商品,直接退出 61 # else: 62 # # 输入不合法 63 # exit_log = True 64 65 # ****************************列表出重适用相连索引,不相连索引****************************** 66 # a_list =[1,1,2,3,3,4,5,3,4] 67 # b_list = [] 68 # for i in a_list: 69 # if i not in b_list: 70 # b_list.append(i) 71 # print(b_list) 72 73 # ****************************列表出重适用不相连索引****************************** 74 # a = [1,2,3,2,3] 75 # b = [] 76 # for i in a: 77 # if i not in b: 78 # b.append(i) 79 # else: 80 # b.remove(i) 81 # print(b) 82 # ***********************map使用*********************** 83 # def square(x) : # 计算平方数 84 # return x ** 2 85 # map(square, [1,2,3,4,5]) # 计算列表各个元素的平方 86 87 # ****************************求列表中不同数值转换成字符串**************************** 88 # a = [1,2,3,2,3] 89 # b = [] 90 # for i in a: 91 # if i not in b: 92 # b.append(i) 93 # else: 94 # b.remove(i) 95 # b = map(str,b) 96 # print(''.join(b)) 97 98 # ****************************求列表中相同数值转换成字符串**************************** 99 # arr = [1,2,3,2,3] 100 # c = [] 101 # for i in range(0, len(arr)): 102 # for j in range(i + 1, len(arr)): 103 # if arr[i] == arr[j]: 104 # c.append(arr[i]) 105 # b = map(str,c) 106 # print(','.join(b)) 107 108 # ***************************列表的垃圾回收机制***************************** 109 # def extendlist(val,list=[]): 110 # list.append(val) 111 # return list 112 # 113 # list1 = extendlist(10) 114 # list2 = extendlist(123,[]) 115 # list3 = extendlist('a') 116 # 117 # print('list1 = %s'%list1) 118 # print('list2 = %s'%list2) 119 # print('list3 = %s'%list3) 120 121 # **************************文件写入操作****************************** 122 # f = open('test','w') 123 # f.write(t) 124 # f.close() 125 126 # **************************1到100相加****************************** 127 # a = sum(range(1,101)) 128 # print(a) 129 130 # **************************int数组考察****************************** 131 # b = int(1.4) 132 # c = int('1.2',16) 133 # print(b,c) 134 135 # ************************求1+2!+3!....+20!的和(就是求1到20阶乘的和)******************************** 136 # s = 0 137 # t = 1 138 # for n in range(1,21): 139 # t *= n 140 # s += t 141 # print(s) 142 143 # ************************************************************************ 144 # n = int(5) 145 # jie = 1 146 # sum = 0 147 # i = 1 148 # while n >= i: 149 # jie = jie * i 150 # sum = sum + jie 151 # i = i + 1 152 # print(sum) 153 154 # *******************************字符串转大写操作******************************** 155 # s = 'nihao' 156 # t = s.upper() 157 158 # *******************************global局部变量转全局变量********************************** 159 # a = 5 160 # def fn(): 161 # global a 162 # a = 4 163 # fn() 164 # print(a) 165 166 # *******************************字典删除/修改操作********************************** 167 # dic = {"name":"zs", "age":18} 168 # del dic['name'] 169 # dic2 = {"name":"la"} 170 # dic.update(dic2) 171 # print(dic) 172 173 # *******************************try使用********************************** 174 # f = open("1.txt","wb") 175 # try: 176 # f.write('hello word') 177 # except: 178 # pass 179 # finally: 180 # f.close() 181 182 # *******************************map计算平方,如果大于10输出********************************** 183 # list = [1,2,3,4,5] 184 # def fn(x) : 185 # return x**2 186 # res = map(fn,list) 187 # res = [i for i in res if i>10] 188 # print(res) 189 190 # *******************************random基础使用********************************** 191 # import random 192 # import numpy 193 # result = random.randint(10,20) 194 # res = numpy.random.randn() 195 # ret = random.random() 196 # print("正整数",result) 197 # print("5个随机小数",res) 198 # print("0-1随机小数",ret) 199 200 # *******************************正则提取中国********************************** 201 # import re 202 # str = '<div class="man">中国</div>' 203 # res = re.findall('<div class=".*">(.*?)</div>', str) 204 # #.代表可有可无;*代表任意字符,满足类名可有变化;(.*?)提取文本 205 # print(res) 206 207 # *******************************lambda(匿名函数)使用********************************** 208 # sum = lambda a,b:a*b 209 # print(sum(4,5)) 210 211 # g = lambda x,y:(x + y) 212 # print(g(10,20)) 213 # def g(x,y): 214 # return x+y 215 # print(g(10,20)) 216 217 # *******************************字典重新key,val排序********************************** 218 # dict={"name":"zs","age":18,"city":"深圳","tel":"1362626627"} 219 # res = sorted(zip(dict.keys(),dict.values())) 220 # # 把字典里元祖转成字典key,val 221 # new_dict = {} 222 # for i in res: 223 # new_dict[i[0]] = i[1] 224 # print(new_dict) 225 226 # ***************利用collections库的Counter方法统计字符串每个单词出现的次数*************** 227 # from collections import Counter 228 # a = "kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h" 229 # res = Counter(a) 230 # print(res) 231 232 # *******************************装饰器使用********************************** 233 # from functools import wraps 234 # import time 235 # def logit(logfile='out.log'): 236 # def logging_decorator(func): 237 # @wraps(func) 238 # def wrapped_function(*args, **kwargs): 239 # log_string = func.__name__ + " was called" 240 # print(log_string) 241 # # 打开logfile,并写入内容 242 # with open(logfile, 'a') as opened_file: 243 # # 现在将日志打到指定的logfile 244 # localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 245 # opened_file.write(log_string+' '+localtime+ '\n') 246 # return func(*args, **kwargs) 247 # return wrapped_function 248 # return logging_decorator 249 # 250 # @logit() 251 # def myfunc1(): 252 # pass 253 # myfunc1() 254 255 # *******************************表处理********************************** 256 # import pandas as pd 257 # io = r'C:\Users\Administrator\PycharmProjects\算法\算法\1.xls' 258 # data = pd.read_excel(io) 259 # print(data[['a','b']]) 260 261 # *******************************a="hello"和b="你好"编码成bytes类型********************************** 262 # a=b"hello" 263 # b="你好".encode() 264 # print(a,b) 265 266 # *******************************统计图********************************** 267 # import numpy as np 268 # from matplotlib import pyplot as plt 269 # 270 # # fname 为 你下载的字体库路径,注意 SimHei.ttf 字体的路径 271 # zhfont1 = matplotlib.font_manager.FontProperties(fname="SimHei.ttf") 272 # 273 # x = np.arange(1, 11) 274 # y = 2 * x + 5 275 # plt.title("菜鸟教程 - 测试", fontproperties=zhfont1) 276 # 277 # # fontproperties 设置中文显示,fontsize 设置字体大小 278 # plt.xlabel("x 轴", fontproperties=zhfont1) 279 # plt.ylabel("y 轴", fontproperties=zhfont1) 280 # plt.plot(x, y) 281 # plt.show() 282 283 # *******************************类的使用********************************** 284 # class Student(): 285 # def __init__(self,user_input_name): 286 # self.name = user_input_name 287 # def say_hi(self): 288 # print('Hello I\'m {}.'.format(self.name)) 289 # 290 # lilei = Student('11111') 291 # lilei.say_hi() 292 293 # *******************************考虑共同类********************************** 294 # import random 295 # class Creatuere(): 296 # def __init__(self,hp,name): 297 # self.hp = hp 298 # self.name = name 299 # 300 # def attack(self): 301 # attack_value = random.randint(0,50) 302 # return attack_value 303 # 304 # def being_attack(self,attack_value): 305 # self.hp = self.hp - attack_value 306 # 307 # def not_dead(self): 308 # if self.hp<0: 309 # return False 310 # else: 311 # return True 312 # def show_status(self): 313 # print('{}\'hp is {}.'.format(self.name,self.hp)) 314 # 315 # player = Creatuere(100,'Bi') 316 # enemy = Creatuere(80,'en') 317 # 318 # while player.not_dead() and enemy.not_dead(): 319 # player.show_status() 320 # enemy.show_status() 321 # user_input = input('attack or defence(A/D)') 322 # if user_input == 'A': 323 # player_attack_value = player.attack() 324 # enemy_attack_value = enemy.attack() 325 # enemy.being_attack(enemy_attack_value) 326 # player.being_attack(player_attack_value) 327 # elif user_input == 'D': 328 # enemy_attack_value = enemy.attack()*0.1 329 # player.being_attack(enemy_attack_value) 330 # 331 # if player.not_dead(): 332 # print('you win!') 333 # else: 334 # print('you los') 335 336 # *******************************用正则过滤掉英文和数字********************************** 337 # import re 338 # a = "not 404 found 张三 99 深圳" 339 # list = a.split(" ") 340 # print(list) 341 # res = re.findall('\d+|[a-zA-Z]+',a) 342 # for i in res: 343 # if i in list: 344 # list.remove(i) 345 # new_str = ''.join(list) 346 # print(res) 347 # print(new_str) 348 349 # *******************************a="张明 98分",用re.sub,将98替换为100********************************** 350 # import re 351 # a="张明 98分" 352 # red = re.sub(r'\d+','100',a) 353 # print(red) 354 355 # *******************************求两个列表的交集、差集、并集********************************** 356 # a = [1, 2, 3, 4] 357 # b = [4, 3, 5, 6] 358 # jj1 = [i for i in a if i in b] 359 # print('交集:',jj1) 360 361 # bj1 = list(set(a).union(set(b))) 362 # print('并集:',bj1) 363 364 # cj1 = list(set(a).difference(set(b))) 365 # print('差集:',cj1) 366 367 # new_list = [] 368 # List = list(set(a + b)) 369 # def git_min(List): 370 # d = min(List) 371 # new_list.append(d) 372 # List.remove(d) 373 # if len(List) >0: 374 # git_min(List) 375 # return new_list 376 # git_min(List) 377 # print('并集:',new_list) 378 379 # *******************************文本操作提取********************************** 380 # 给出一个文本文件,包含用户访问记录,每一行为id,user_id,日期,比如“j354kdfd,82242,2018-09-18”, 381 # 请给出每年的用户平均访问次数。比如2018年有两个用户,分别访问了8,6次,那么2018年的用户平均访问次数是7 382 383 # import pandas as pd 384 # f = pd.read_csv('test.csv') 385 # a = f[f['日期'].str.contains("2018")] 386 # print(a) 387 # d = f[(f['id'] == "'aaaaaaaa'") & (f['日期'].str.contains("2018"))] 388 # d1 = f[(f['id'] == "'j354kdfd'") & (f['日期'].str.contains("2018"))] 389 # print((len(d) + len(d1)) / 2) 390 391 # *******************************join使用********************************** 392 # x="123" 393 # y="321" 394 # z=["4","5","6"] 395 # print(x.join(y),x.join(z)) 396 397 # *******************************打印当前时间戳********************************** 398 # import datetime 399 # a = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + ' 星期:' + str(datetime.datetime.now().isoweekday()) 400 # print(a) 401 402 # *******************************字符串操作********************************** 403 # 字符串操作:实现 split E函数,函数定义为 def split(txt, delimiter)), 404 # 比如:输入abcbbcc","bc",输出{'a','b','c'} 405 406 # def split(txt,delimiter): 407 # print(sorted(set(txt+delimiter))) 408 # split("abcbbcc","bc") 409 410 # *******************************字典和json字符串相互转化********************************** 411 # import json 412 # dic = {'name':'zs'} 413 # res = json.dumps(dic) 414 # print(type(res)) 415 # ret = json.loads(res) 416 # print(ret) 417 418 # *******************************列表推导式求列表所有奇数并构造新列表********************************** 419 # a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 420 # b = [i for i in a if i%2==0] 421 # print(b) 422 423 424 # *******************************列表嵌套字典的排序********************************** 425 # foo = [{"name":"zs","age":19},{"name":"ll","age":54},{"name":"wa","age":17},{"name":"df","age":23}] 426 # a = sorted(foo,key=lambda x : x['age'],reverse=True ) 427 # print(a) 428 # b = sorted(foo,key=lambda x:x['name']) 429 # print(b) 430 431 432 #*******************************写一段自定义异常代码********************************** 433 # def f(): 434 # try: 435 # for i in range(5): 436 # if i>2: 437 # raise Exception('数字大于2') 438 # except Exception as e: 439 # print(e) 440 # f() 441 442 #*******************************使用pop和del删除字典中的字段********************************** 443 # dic={"name":"zs","age":18} 444 # dic.pop('name') 445 # print(dic) 446 # dic={"name":"zs","age":18} 447 # del dic['name'] 448 # print(dic) 449 450 #*******************************不许用sort,输出排序********************************** 451 # list=[2,3,5,4,9,6],从小到大排序,不许用sort,输出[2,3,4,5,6,9] 452 # 利用min()方法求出最小值,原列表删除最小值,新列表加入最小值,递归调用获取最小值的函数,反复操作 453 454 # List = [2, 3, 5, 4, 9, 6] 455 # New_list = [] 456 # 457 # def get_min(List): 458 # a = min(List) 459 # New_list.append(a) 460 # List.remove(a) 461 # if len(List) > 0: 462 # get_min(List) 463 # return New_list 464 # 465 # Newlist = get_min(List) 466 # print(Newlist) 467 468 #*******************************map 与 filter 函数区别********************************** 469 # res1 = map(lambda n: n > 5, range(10)) 470 # lt1 = list(res1) 471 # print(lt1) 472 # 473 # res2 = filter(lambda n: n > 5, range(10)) 474 # lt = list(res2) 475 # print(lt) 476 477 #*******************************csv文件处理********************************** 478 # import pandas as pd 479 # import os 480 # f = 'C:/Users/Administrator/PycharmProjects/Hello python/面试题/csv文件夹' 481 # for filename in os.listdir(f): 482 # data = pd.read_csv(f+'/'+filename, names=['列1', '列2', '列3', '列4', '列5']) 483 # data = pd.DataFrame(data.mean()).T.rename(index = {0:filename}) 484 # print(data) 485 # data.to_csv('result.csv',mode='a+',header=0) 486 487 # data = pd.DataFrame({ 488 # 'tag_id':['a','b','c','a','a','c'], 489 # 'count':[10,30,20,10,15,22] 490 # }) 491 # grouped_data = data.groupby('列1') 492 493 494 #*******************************api的使用********************************** 495 # import requests 496 # def weather_api(question): 497 # url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + question 498 # res = requests.get(url).json() 499 # print(res['data']['yesterday']) 500 # city = input('请输入城市:') 501 # weather_api(city) 502 503 #*******************************[[1,2],[3,4],[5,6]]一行代码展开该列表,得出[1,2,3,4,5,6]********************************** 504 # a = [[1,2],[3,4],[5,6]] 505 # b = [j for i in a for j in i] 506 # print(b)