2018.10.10python homework
Posted CUIHUANIHAO
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2018.10.10python homework相关的知识,希望对你有一定的参考价值。
names=[‘egon‘,‘alex_sb‘,‘wupeiqi‘,‘yuanhao‘]
new_names=[name.upper() for name in names]
print(new_names)
2、将names=[‘egon‘,‘alex_sb‘,‘wupeiqi‘,‘yuanhao‘]中以sb结尾的名字过滤掉,然后保存剩下的名字
长度。
names=[‘egon‘,‘alex_sb‘,‘wupeiqi‘,‘yuanhao‘]
res=filter(lambda name:not name.endswith(‘sb‘),names)
print(list(res))
3、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)
with open(‘a.txt‘,‘rt‘,encoding=‘utf-8‘)as f:
res=max(f,key=lambda line:len(line))
print(len(res))
4、求文件a.txt中总共包含的字符个数?思考为何在第一次之后的n次sum求和得到的结果为0?(需要使用sum函数)
with open(‘a.txt‘,‘rt‘,encoding=‘utf-8‘)as f:
res=sum(len(line) for line in f)
print(res)
5、思考题
with open(‘a.txt‘) as f:
g=(len(line) for line in f)
print(sum(g)) #为何报错?
f= open(‘a.txt‘)
g=(len(line) for line in f)
f.close()
print(sum(g))
#这两个报错是一致的,所以可能是后面再求和的时候文件已经关闭了
6、文件shopping.txt内容如下:
mac,20000,3
lenovo,3000,10
tesla,1000000,10
chicken,200,1
求总共花了多少钱?
#方式一:
with open(‘shopping.txt‘)as f:
money=0
for msg in f:
res=msg.strip(‘
‘).split(‘,‘)
sums=int(res[1])*int(res[2])
money+=sums
print(money)
方式二:
with open(‘shopping.txt‘,encoding=‘utf-8‘) as f:
info=[line.split(‘,‘) for line in f]
money=sum(float(price)*int(count) for *_,price,count in info)
print(money)
打印出所有商品的信息,格式为[{‘name‘:‘xxx‘,‘price‘:333,‘count‘:3},...]
#方式一:
products=[]
with open(‘shopping.txt‘)as f:
for msg in f:
res = msg.strip(‘
‘).split(‘,‘)
res_dict={‘name‘:res[0],‘price‘:res[1],‘count‘:res[2]}
products.append(res_dict)
print(products)
#方式二:
with open(‘shopping.txt‘)as f:
info=[{‘name‘:line.strip(‘
‘).split(‘,‘)[0],‘price‘:line.strip(‘
‘).split(‘,‘)[1],‘count‘:line.strip(‘
‘).split(‘,‘)[2]} for line in f]
print(info)
求单价大于10000的商品信息,格式同上
products=[]
with open(‘shopping.txt‘)as f:
for msg in f:
res = msg.strip(‘
‘).split(‘,‘)
res_dict={‘name‘:res[0],‘price‘:res[1],‘count‘:res[2]}
if int(res_dict[‘price‘])>10000:
products.append(res_dict)
print(products)
7.想从一个按照从小到大排列的数字列表中找到指定的数字,遍历的效率太低,用二分法(算法的一种,算法是解决问题的方法)可以极大低缩小问题规模
nums=[1,2,10,30,33,99,101,200,301,311,402,403,500,900,1000] #从小到大排列的数字列表
def search_num(num,nums):
if len(nums) == 0:
print(‘num not exist‘)
return
mid_index=len(nums)//2
if num > nums[mid_index]:
nums=nums[mid_index+1:]
search_num(num,nums)
elif num < nums[mid_index]:
nums=nums[:mid_index]
search_num(num,nums)
else:
print(‘got it‘)
search_num(44,nums)
l = [1, 2, 10, 30, 33, 99, 101, 200, 301, 402]
def search_index(num, l, start=0, stop=len(l) - 1):
if start <= stop:
mid_index = start + (stop - start) // 2
if num > l[mid_index]:
start = mid_index + 1
?
elif num < l[mid_index]:
stop = mid_index - 1
else:
print(‘got it‘, mid_index)
return
search_index(num, l, start, stop)
else:
print(‘num not exist‘)
return
?
?
search_index(33, l)
以上是关于2018.10.10python homework的主要内容,如果未能解决你的问题,请参考以下文章