功能代码块
Posted rongge95500
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了功能代码块相关的知识,希望对你有一定的参考价值。
二分法
想从一个按照从小到大排列的数字列表中找到指定的数字,遍历的效率太低,用二分法(算法的一种)可以极大缩小问题规模
1 l=[1,3,5,8,12,34,45,56,67,78,89,123,234,345,456,566,789] 2 def find(find_num,l): 3 print(l) 4 if len(l)==0: 5 print(‘not find‘) 6 return 7 mid_index=len(l)//2 8 if find_num>l[mid_index]: 9 l=l[mid_index+1:] 10 find(find_num,l) 11 elif find_num<l[mid_index]: 12 l=l[:mid_index] 13 find(find_num,l) 14 else: 15 print(‘find it‘) 16 find(45,l)
购物车项目
1 import os 2 3 product_list = [[‘Iphone7‘, 5800], 4 [‘Coffee‘, 30], 5 [‘疙瘩汤‘, 10], 6 [‘Python Book‘, 99], 7 [‘Bike‘, 199], 8 [‘ViVo X9‘, 2499], 9 ] 10 11 DB = r‘bc.txt‘ 12 shopping_cart = {} 13 user_info = [] 14 15 while True: 16 print(‘‘‘ 17 1: register 18 2: login 19 3: shopping 20 ‘‘‘) 21 22 choice = input(‘请选择>>:‘).strip() 23 if choice == ‘1‘: 24 print(‘register‘) 25 while True: 26 name = input(‘输入用户名>>:‘).strip() 27 pwd = input(‘输入密码>>:‘).strip() 28 conf_pwd = input(‘再次输入密码>>:‘).strip() 29 if not pwd == conf_pwd: 30 print(‘密码输入错误‘) 31 continue 32 print(‘注册成功‘) 33 34 balance = input(‘请输入充值金额>>:‘).strip() 35 print(‘充值成功‘) 36 break 37 with open(DB, ‘at‘, encoding=‘utf-8‘) as f: 38 f.write(‘%s|%s|%s‘ % (name, pwd, balance)) 39 f.flush() 40 41 42 elif choice == ‘2‘: 43 print(‘login‘) 44 count = 0 45 tag = True 46 if count == 3: 47 print(‘尝试次数过多,退出。。。‘) 48 break 49 while tag: 50 name = input(‘输入用户名>>:‘).strip() 51 pwd = input(‘输入密码>>:‘).strip() 52 with open(DB, ‘r‘, encoding=‘utf-8‘) as f: 53 for line in f: 54 # 将字符串切成列表 55 line = line.strip(‘ ‘) 56 info_line = line.split(‘|‘) 57 58 # 分别取出用户名、密码、余额 59 db_name = info_line[0] 60 db_pwd = info_line[1] 61 db_balance = int(info_line[2]) 62 63 if name == db_name and pwd == db_pwd: 64 print(‘登录成功‘) 65 user_info = [db_name, db_balance] 66 print(‘当前用户信息:‘, user_info) 67 tag = False 68 break 69 else: 70 print(‘用户名或密码错误‘) 71 count += 1 72 73 74 elif choice == ‘3‘: 75 print(‘shopping‘) 76 if len(user_info) == 0: 77 print(‘请先登录,谢谢‘) 78 else: 79 80 # 打印当前登录用户信息 81 db_name = user_info[0] 82 db_balance = user_info[1] 83 print(‘用户信息‘.center(50, ‘-‘)) 84 print(‘‘‘尊敬的用户 %s 85 您的可用余额为 %s 元 86 ‘‘‘ % (db_name, db_balance)) 87 print(‘祝您购物愉快‘.center(50, ‘-‘)) 88 tag = True 89 while tag: 90 91 # 循环打印带有索引的购物清单 92 for k, v in enumerate(product_list): 93 print(k, v) 94 choice = input(‘选择商品编号或按(q)退出>>:‘).strip() 95 if choice.isdigit(): 96 choice = int(choice) 97 if choice < 1 or choice > 6: # 判断用户的选择是否在索引范围之内 98 print(‘没有该商品,请重试‘) 99 continue 100 101 # 取出商品信息进行判断 102 goods_name = product_list[choice][0] 103 goods_price = product_list[choice][1] 104 105 if db_balance > goods_price: # 余额大于商品价格时购买 106 107 if goods_name in shopping_cart: 108 shopping_cart[goods_name][‘count‘] += 1 # 商品已存在时购物车内的商品个数加一 109 else: 110 shopping_cart[goods_name] = {‘price‘: goods_price, ‘count‘: 1} # 不存在新加商品 111 112 db_balance -= goods_price 113 user_info[1] = db_balance # 用户每选择一个商品后将余额更新一次 114 else: 115 print(‘余额不足‘) 116 print(shopping_cart) 117 118 elif choice == ‘q‘: 119 print(shopping_cart) 120 while tag: 121 buy = input(‘确认购买商品吗(y/n)>>:‘).strip() 122 if buy == ‘Y‘ or buy == ‘y‘: 123 old_file = DB 124 new_file = r‘%s.swap‘ % DB # 购买之后写入文件 125 with open(old_file, ‘r‘, encoding=‘utf-8‘) as read_f, 126 open(new_file, ‘w‘, encoding=‘utf-8‘) as write_f: 127 for line in read_f: 128 if line.startswith(db_name): 129 l = line.strip(‘ ‘).split(‘|‘) # 将字符串切成列表 130 l[-1] = str(db_balance) # 修改余额 131 line = ‘|‘.join(l) + ‘ ‘ # 重新拼回字符串 132 133 write_f.write(line) 134 os.remove(old_file) 135 os.rename(new_file, old_file) 136 137 print(‘购买成功‘) 138 139 shopping_cart = {} 140 user_info = [] 141 tag = False 142 143 else: 144 print(‘输入错误,重试‘) 145 146 else: 147 print(‘输入错误,请重试‘)
装饰器(用户登录认证)
def login_auth(func): def wrapper(*args, **kwargs): ‘‘‘ :param args: :param kwargs: :return: ‘‘‘ return func(*args, **kwargs) return wrapper
单例模式的实现
#settings.py
IP=‘1.1.1.2‘ PORT=3302
1 # 一:在内部定义一个类 2 import settings 3 4 5 class mysql: 6 __instance = None 7 8 def __init__(self, ip, port): 9 self.ip = ip 10 self.port = port 11 12 @classmethod 13 def conf(cls): 14 if cls.__instance is None: 15 cls.__instance = cls(settings.IP, settings.PORT) 16 return cls.__instance 17 18 19 obj = Mysql.conf() 20 obj1 = Mysql.conf() 21 obj2 = Mysql.conf() 22 print(obj) 23 print(obj1) 24 print(obj2)
1 # 二:用装饰器 2 import settings 3 4 5 def singleton(cls): 6 cls.__instance = cls(settings.IP, settings.PORT) 7 8 def wrapper(*args, **kwargs): 9 if len(args) == 0 and len(kwargs) == 0: 10 return cls.__instance 11 return cls(*args, **kwargs) 12 13 return wrapper 14 15 16 @singleton 17 class Mysql: 18 def __init__(self, ip, port): 19 self.ip = ip 20 self.port = port 21 22 23 obj = Mysql() 24 obj1 = Mysql() 25 print(obj) 26 print(obj1)
1 # 三:元类 2 import settings 3 4 5 class Mymeta(type): 6 def __init__(self, class_name, class_bases, class_dic): 7 super(Mymeta, self).__init__(class_name, class_bases, class_dic) 8 self.__instance = self.__new__(self) 9 self.__init__(self, settings.IP, settings.PORT) 10 11 def __call__(self, *args, **kwargs): 12 if len(args) == 0 and len(kwargs) == 0: 13 return self.__instance 14 15 obj = self.__new__(self) 16 self.__init__(obj, *args, **kwargs) 17 return obj 18 19 20 class Mysql(object, metaclass=Mymeta): 21 def __init__(self, ip, port): 22 self.ip = ip 23 self.port = port 24 25 26 obj = Mysql() 27 obj1 = Mysql() 28 print(obj) 29 print(obj1)
进度条
1 def grogress_bar(percent, width): 2 if percent > 1: percent = 1 3 show_str = (‘%%-%ds‘ % width) % (int(percent * width) * ‘#‘) 4 print(‘ %s%% %s‘ % (int(percent * 100), show_str), end=‘‘) 5 6 7 total_size = 123451 8 recv_size = 0 9 while total_size > recv_size: 10 time.sleep(0.2) 11 recv_size += 1024 12 percent = recv_size / total_size 13 grogress_bar(percent, width=40)
随机码
1 def hatted_code(n): 2 res=‘‘ 3 for i in range(n): 4 num=str(random.randint(0,9)) 5 alp=chr(random.randint(65,90)) 6 res+=random.choice([num,alp]) 7 return res 8 print(hatted_code(4))
以上是关于功能代码块的主要内容,如果未能解决你的问题,请参考以下文章