8.2每日作業系列之函數的遞歸調用
阿新 • • 發佈:2018-08-11
nco 所有 NPU put count == fin odi line
# 1 使用遞歸打印斐波那契數列(前兩個數的和得到第三個數,如:0 1 1 2 3 4 7...)
# def func(x,y):
# res=x+y
# print(x)
# if res<100:
# return func(y,res)
# else:
# return y
# print(func(0,1))
# 2 一個嵌套很多層的列表,如l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]],用遞歸取出所有的值
# l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]]
# def func(l):
# for i in l:
# if type(i) is not list:
# print(i)
# else:
# func(i)
# func(l)
# 3 編寫用戶登錄裝飾器,在登錄成功後無需重新登錄,同一賬號重復輸錯三次密碼則鎖定5分鐘
# import time
# def outter(func):
# def wrapper(*args,**kwargs):
# count = 0
# while True:
# if count == 3:
# time.sleep(10)
# wrapper()
# name = input(‘用戶名:‘).strip()
# pwd = input(‘密碼:‘).strip()
# with open(‘db.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
# for line in f:
# if line.startswith(name):
# line = line.strip(‘\n‘).split(‘,‘)
# if line[1]==pwd:
# if line[3]:
# print(‘已登陸‘)
# return
# print(‘登陸成功‘)
# res=func(*args,**kwargs)
# return res
# else:
# print(‘密碼錯誤‘)
# count+=1
# return wrapper
#
# @outter
# def index():
# print(‘.......‘)
# time.sleep(4)
# index()
# 4、求文件a.txt中總共包含的字符個數?思考為何在第一次之後的n次sum求和得到的結果為0?(需要使用sum函數)
# with open(‘db.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
# print(sum(len(line) for line in f))
# 5、文件shopping.txt內容如下
# mac,20000,3
# lenovo,3000,10
# tesla,1000000,10
# chicken,200,1
# 求總共花了多少錢?
with open(‘info.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
# # info=[line.strip(‘\n‘).split(‘,‘) for line in f]
# # cost=sum(float(price)*int(count) for _,price,count in info)
# # print(cost)
#
l=[]
for line in f:
info=line.strip(‘\n‘).split(‘,‘)
name,price,count=info
res=float(price)*int(count)
l.append(res)
cost=sum(l)
print(cost)
# for line in f:
# info=line.strip(‘\n‘).split(‘,‘)
# for _, price, count in info:
# print(_, price, count)
# for i in info:
# print(i)
# 打印出所有商品的信息,格式為[{‘name‘:‘xxx‘,‘price‘:333,‘count‘:3},...]
# with open(‘info.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
# info=[{
# ‘name‘: line.strip(‘\n‘).split(‘,‘)[0],
# ‘price‘: float(line.strip(‘\n‘).split(‘,‘)[1]),
# ‘count‘: int(line.strip(‘\n‘).split(‘,‘)[2]),
# } for line in f]
# print(info)
# 求單價大於10000的商品信息,格式同上
# with open(‘info.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
# info=[{
# ‘name‘: line.strip(‘\n‘).split(‘,‘)[0],
# ‘price‘: float(line.strip(‘\n‘).split(‘,‘)[1]),
# ‘count‘: int(line.strip(‘\n‘).split(‘,‘)[2]),
# } for line in f if float(line.strip(‘\n‘).split(‘,‘)[1]) > 10000]
# print(info)
# 明日默寫:
# 二分查找
# l=[1,2,10,30,33,99,101,200,301,311,402,403,500,900,1000] #從小到大排列的數字列表
# def search(n,l):
# print(l)
# if len(l) == 0:
# print(‘not exists‘)
# return
# mid_index=len(l) // 2
# if n > l[mid_index]:
# #in the right
# l=l[mid_index+1:]
# search(n,l)
# elif n < l[mid_index]:
# #in the left
# l=l[:mid_index]
# search(n,l)
# else:
# print(‘find it‘)
# search(3,l)
8.2每日作業系列之函數的遞歸調用