知行合一
Choose a quality life!

1:   要点是在if 判断那里,根据条件迭代替换                sum(*args)  可以求和

接收n个参数. 返回最大值和最小值(字典)

 def func(*args):

     m = args[0] # 假设第0项就是最大值
     mi = args[0]
     for el in args:
         if el > m:
             m = el # 当前这个元素比假设的那个大. 记录当前这个比较大的数
         if el < mi:
             mi = el
 return {"最大值":m, "最小值":mi}

 print(func(5,7,12,1,46,87,3))

 

2:

user_list=[
{"name": "alex", "hobby": "抽烟"},
{"name": "alex", "hobby": "喝酒"},
{"name": "alex", "hobby": "烫头"},
{"name": "wusir", "hobby": "喊麦"},
{"name": "wusir", "hobby": "街舞"},
{"name": "alex", "hobby": "泡吧"},
{"name":"太白", "hobby":"开车"}
]

 

result = [] # {'name': 'alex', 'hobby_list': ['抽烟']}
# 1.判断是否在result里面存在了这个人, 如果存在. 把hobby_list添加一个hobby

# 2.不存在. 创建一个新字典

for user in user_list:
    for new_user in result:
        if user['name'] == new_user['name']:
        new_user['hobby_list'].append(user['hobby'])
        break
else:
dic = {}
dic["name"] = user['name']
dic['hobby_list'] = [user['hobby']]
result.append(dic)
print(result)

 

 

3:

def add(a, b):
    return a + b

def gen():

    for r_i in range(4):
    yield r_i

g = gen()

for n in [2, 10]:
    g = (add(n, i) for i in g)
print(list(g))     用到的是生成器表达式的惰性机制

 

 

4:

 


一,冒泡排序:
中心思想:
a,b = b,a

lis = [56,66,23,45,12,3,4,62]
count = 0
while count <= len(lis):
for i in range(len(lis)-1):
if lis[i] > lis[i+1]:
lis[i],lis[i+1] = lis[i+1],lis[i]
count = count + 1
print(lis)
二,升序的内置函数
lis = [56,66,23,45,12,3,4,62]
lis1 = sorted(lis) # 这是一个升序的内置函数
print(lis1)

三,二分法
lis = [3, 4, 12, 23, 45, 56, 62, 66]
a = 62
left = 0
right = len(lis) - 1
count = 1
while left <= right:
middle = (left + right) // 2
if a > lis[middle]:
left = middle + 1
elif a < lis[middle]:
right = middle - 1
else:
print(count)
print(lis[middle])
break
count = count + 1
else:
print('您找的数字不存在.')
用函数的递归来循环调用函数体,利用return返回值来判断数字的位子
lst = [11,22,33,44,55,66,77,88,99,123,234,345,456,567,678,789,1111]
def binary_search(left, right, n):
middle = (left + right)//2
if left > right:
return -1
if n > lst[middle]:
left = middle + 1
elif n < lst[middle]:
right = middle - 1
else:
return middle
return binary_search(left, right, n) # 这个return是用来接第二次调用,返回值的 ,
print(binary_search(0, len(lst)-1, 123) )
posted on 2018-07-17 21:39  小米没吃饭  阅读(194)  评论(0编辑  收藏  举报