1. 找出字典中的最大值
max_info = {"A": 12, "B": 222, "C": 44}
print(max(max_info.values())) # 222
print(max(max_info, key=lambda x: max_info[x])) #B
print(max(max_info.items(), key=lambda x: x[1])) # ("B", 222)
print(max(max_info, key=max_info.get)) # B
print(max(zip(max_info.values(), max_info.keys()))) # (222, "B")
2.求n*n的二维数组的对角线之和
def array_sum(list_info):
"""n*n的矩阵对角线的和"""
num = 0
for i in range(len(list_info)):
for j in range(len(list_info)):
array1 = list_info[i]
array2 = array1[j]
if i == j or i + j == len(list_info) - 1:
print('i=', i, 'j=', j, 'array2=', array2)
num += array2
print(num)
array_sum([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
3.倒水问题
little_cup = int(input("请输入小水杯容量:"))
big_cup = int(input("请输入大水杯容量:"))
target = int(input("请输入目标体积水容量:"))
"""
小杯不断往大杯中倒水
大杯满了大杯全部倒掉
小杯继续往大杯倒水,直到得到目标水量,或者得不到目标水量退出循环
"""
i = 2
while True:
if little_cup < big_cup:
first_result = little_cup % big_cup
if first_result == target:
print("得到目标水量:{}".format(first_result))
break
elif target < big_cup:
result = (little_cup * i) % big_cup
i += 1
if result == target:
print("已经成功得到目标水量:{}".format(result))
break
elif result == first_result:
print("无法得到目标水量")
break
4.找出列表中出现频率最高的元素
from collections import Counter
"""1613. 最高频率的IP
给定一个字符串数组lines, 每一个元素代表一个IP地址,找到出现频率最高的IP。
样例2:
输入 = ["192.168.1.1","192.118.2.1","192.168.1.1","192.118.2.1","192.118.2.1"]
输出 "192.118.2.1"
注意事项
给定数据只有一个频率最高的IP"""
class Solution:
def highest_Frequency(self, iplines):
# return Counter(iplines).most_common()[0][0] # 方法1
# dict1 = {}
# for key in iplines:
# dict1[key] = dict1.get(key, 0)+1
# return max(dict1.keys(), key=lambda x: x[1]) #方法2
ans = iplines[0]
mapdic = {} # 记录每个ip出现的次数
for ip in iplines:
if ip in mapdic:
mapdic[ip] += 1
# print("mapdic:{}".format(mapdic))
else:
mapdic[ip] = 1
max = 0
# 遍历出出现次数最大
for key in mapdic:
if int(mapdic[key]) > max:
# 如果大于最大次数,则替换
max = mapdic[key]
key = ans
return ans
print(Solution().highest_Frequency(
["192.168.1.1", "192.118.2.1", "192.168.1.1", "192.118.2.1", "192.118.2.1", "192.168.1.1", "192.168.1.1"]))
print(Solution().highest_Frequency(["192.168.1.1", "192.118.2.1", "192.168.1.1"]))
找出列表中出现频率最高的元素
a = [1, 3, 4, 5, 6, 6, 6 ,6, 6]
# 方法一
count_dict = {}
for i in a:
# 元素没有在字典时,初始化赋值
if i not in count_dict:
count_dict[i] = 1
# 元素已在字典中,累加统计
else:
count_dict[i] += 1
print(max(count_dict.keys()))
# 方法二
count_dict_j = {}
for j in a:
count_dict_j[j] = count_dict_j.get(j, 1) + 1
print(max(count_dict_j.keys()))