有一個從小到大排列的整形數字列表,咱們判斷某一個數字是否是在這個列表裏面。git
動用二分法查找數字編程
import time def rec_find_num(num, lis): """遞歸版本""" lis_len = int(len(lis) / 2) # 10.0 binary_num = lis[lis_len] # 10 if len(lis) == 1: print('沒找到') return if binary_num > num: lis = lis[:lis_len] rec_find_num(num, lis) elif binary_num < num: # 10 < 18 lis = lis[lis_len + 1:] rec_find_num(num, lis) else: print('找到了') lis = [i for i in range(100000000)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] start = time.time() rec_find_num(4567899900, lis) end = time.time() print(end - start) # 1.1569085121154785 import time lis = [i for i in range(100000000)] def time_count(func): def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() print(end - start) return res return wrapper
@time_count def find_num(num): """普通版本""" for i in lis: if i == num: print('找到了') break else: print('沒有被找到') find_num(4567899900) # 2.293410062789917
有名函數:有名字的函數app
def laowang(): pass laowang()
匿名函數:沒有綁定名字,使用一次即被收回,加括號能夠運行dom
lambda關鍵字定義aiphone
#語法: lambda x,y(參數):x+y(邏輯代碼) res=(lambda x,y:x+y)(1,2) print(res) ----->3
匿名函數也能調用,可是調用須要注意只能使用一次,通常不單獨使用。函數
與內置函數聯用:匿名函數一般與max()、min()、map()、sorted()、filter()方法聯用翻譯
salary_dict = {j 'nick': 3000, 'jason': 100000, 'tank': 5000, 'sean': 2000, 'tttt': 4000, 'egon': 10000000, } #咱們要找到工資最高的那我的 max() max_salary = max(iterable) # 按照鍵取最大 # jnst # tttt print(max_salary) def key(res): # res='nick','tank' return iterable[res] max_salary = max(iterable, key=key) print(max_salary) #1. salary_dict變成迭代器對象salary_dict_iter #2. res = salary_dict_iter.__next__ #3. res丟入函數func中,3000,100000,5000,2000,4000 #4. 獲得函數的返回值,把這個返回值做爲判斷依據 #5. 只要把值丟到max函數裏,就能夠找到最大值
掌握:code
bytes() :解碼字符對象
chr()ord() :chr()參考ASCII碼錶將數字轉化爲對應字符; ord()將字符轉化爲對應的數字
print(chr(65))
A
print(ord('A'))
65
divmod() :分欄
enumerate() :帶有索引的迭代
eval() :把字符串翻譯成數據類型
hash() :是否可哈希
解碼字符
例如:機選一組雙色球
import random print([random.randint(1,32) for i in range(6)]) lis = [] for i in range(12): if len(lis)==6: break num = random.randint(1,32) if num in lis: pass else: lis.append(num) print(lis)
例如:
一個瓶子的工廠:
原材料(一堆熟料)
融化塑料
經過模具作出一個瓶子
包裝檢測瓶子
買瓶子
按照必定的順序,瞬息中的每一步均可以當作函數,這個函數是上一個函數的輸出,這就叫面向過程編程
優勢:1. 邏輯清晰,簡單明瞭
2. 每一個函數能夠獨立的寫出來
缺點:1. 相互之間會有聯繫,上一部中斷了,下一步也就中斷了
2.有一個功能改變了,其餘的功能也要改變
3.可擴展性差
例如:
shopping_car_dict = dict() # 存儲購買商品 user_info_dict = dict() # 記錄用戶登錄信息 goods_price_total = 0 # 總價 def input_username_pwd(): """輸入用戶名/密碼""" username = input('請輸入你的名字》》》') pwd = input('請輸入你的密碼》》》') return username, pwd def save_file_a(filename, content): """a模式保存文件""" with open(filename, 'a', encoding='utf8') as fa: fa.write(content) return True def save_file_w(filename, content): """w模式保存文件""" with open(filename, 'w', encoding='utf8') as fw: fw.write(content) return True def read_file(filename): """讀取文件""" with open(filename, 'r', encoding='utf8') as fr: data_list = fr.readlines() return data_list def login_deco(func): def wrapper(*args, **kwargs): if not user_info_dict: login_res = login() if login_res: res = func(*args, **kwargs) return res else: print('登錄失敗,請從新登錄') return res = func(*args, **kwargs) return res return wrapper def register(): """註冊""" print("\033[1;31;40m歡迎使用註冊功能\033[0m") while True: username, pwd = input_username_pwd() # 判斷用戶名是否已經存在 user_info_data_list = read_file('user_info.txt') for user_info in user_info_data_list: user_list = user_info.strip().split(':') username_file = user_list[0] if username_file == username: print('用戶名已經存在,請從新註冊') break else: save_file_a('user_info.txt', f'{username}:{pwd}:15000:0\n') break def login(): """登錄,登錄三次後退出""" print("\033[1;31;40m歡迎使用登錄功能\033[0m") count = 0 while count < 3: username, pwd = input_username_pwd() # 判斷用戶是否存在 user_info_data_list = read_file('user_info.txt') for user_info in user_info_data_list: # 姓名:密碼:餘額:鎖 user_list = user_info.strip().split(':') username_file = user_list[0] pwd_file = user_list[1] extra = int(user_list[2]) lock_num = user_list[3] lock_num_int = int(lock_num) if username == username_file and pwd == pwd_file: if lock_num_int == 0: print('登錄成功') # 存放用戶信息 user_info_dict['username'] = username_file user_info_dict['pwd'] = pwd_file user_info_dict['extra'] = extra user_info_dict['lock_num'] = lock_num return True else: print('帳戶被凍結') return False else: # for循環沒有被break/return後執行 count += 1 print('帳戶名/密碼錯誤,請從新登錄') @login_deco def shopping(): """購物""" print("\033[1;31;40m歡迎使用購物功能\033[0m") goods_dict = { '0': ('tesla', 100), '1': ('tiger', 1000), '2': ('nick全*寫真集', float("inf")), '3': ('nick半*寫真集', float("inf") / 2), '4': ('iphoneX', 10), '5': ('MacPro', 15), 'q': '退出' } while True: for ind, goods in goods_dict.items(): print(ind, goods) goods_choice = input('請選擇你須要購買的商品號(輸入q退出)》》》').strip() if goods_choice == 'q': break if goods_choice not in goods_dict: print('傻逼,眼瞎,滾走,討厭~!') continue goods_num_choice = input('請輸入你須要購買的商品數量(輸入q退出)》》》').strip() if goods_num_choice == 'q': break if not goods_num_choice.isdigit(): print('傻逼,你數學體育老師教的???') continue goods_num_choice_int = int(goods_num_choice) shopping_goods = goods_dict[goods_choice] print(f'你購買的{shopping_goods} {goods_num_choice_int}已經加入購物車,請進入購物車結帳!') if not shopping_car_dict.get(shopping_goods): shopping_car_dict[shopping_goods] = goods_num_choice_int else: shopping_car_dict[shopping_goods] += goods_num_choice_int @login_deco def shopping_car(): """購物車""" print("\033[1;31;40m歡迎使用購物車功能\033[0m") global goods_price_total while True: # 打印購物車信息+計算總價 print('你的購物車有以下產品:') for shopping_goods, goods_num in shopping_car_dict.items(): print(shopping_goods, goods_num) goods_price_total += shopping_goods[1] * goods_num if goods_price_total > user_info_dict['extra']: print('窮逼,餘額不足,沒法購買,平臺沒法充值,請修改or請滾蛋!!!') # 修改購物車 while True: for ind, goods in enumerate(shopping_car_dict): print(ind, goods) shopping_car_list = [goods for _, goods in enumerate(shopping_car_dict)] modify_goods_ind = input('請選擇你須要修改的商品編號》》》').strip() modify_goods = shopping_car_list[int(modify_goods_ind)] modify_goods_num = int(input('請選擇你須要修改的商品數量》》》').strip()) shopping_car_dict[modify_goods] = modify_goods_num break else: print('你能夠去結帳了') break @login_deco def check(): """結帳""" print("\033[1;31;40m歡迎使用結帳功能\033[0m") if goods_price_total <= user_info_dict['extra']: user_info_dict['extra'] -= goods_price_total # 清空購物車 global shopping_car_dict shopping_car_dict = dict() print(f'結帳{goods_price_total}成功,你餘額爲{user_info_dict["extra"]}') else: print('餘額不足,請前往購物車修改商品信息') shopping_car() @login_deco def lottery(): # 抽獎 """抽獎""" print("\033[1;31;40m歡迎使用抽獎功能\033[0m") pass @login_deco def goods_back(): """退貨""" print("\033[1;31;40m歡迎使用退貨功能\033[0m") pass @login_deco def coupon(): """優惠券""" print("\033[1;31;40m歡迎使用優惠券功能\033[0m") pass @login_deco def shopping_history(): """消費記錄""" print("\033[1;31;40m歡迎使用消費記錄功能\033[0m") pass '**************************************************' func_dict = { 0: register, 1: login, 2: shopping, 3: shopping_car, 4: check, 5: lottery, # 抽獎 6: goods_back, 7: coupon, 8: shopping_history, } func_msg = """ 0:註冊, 1:登陸, 2:購物, 3:購物車, 4:結帳, 5:抽獎 6:退貨, 7:優惠券, 8:消費記錄, q:退出 """ while True: print(func_msg) func_choice = input('請輸入你想要使用的功能(輸入q退出)》》》').strip() # 退出 if func_choice == 'q': break # 判斷是否非法輸入 if not func_choice.isdigit(): print('非法輸入') continue # 判斷是否非法輸入 func_choice_int = int(func_choice) if func_choice_int not in func_dict: print('非法輸入') continue # 正常選擇功能 func_dict[func_choice_int]()