1. 找出字典中的最大值

  1. max_info = {"A": 12, "B": 222, "C": 44}
  2. print(max(max_info.values())) # 222
  3. print(max(max_info, key=lambda x: max_info[x])) #B
  4. print(max(max_info.items(), key=lambda x: x[1])) # ("B", 222)
  5. print(max(max_info, key=max_info.get)) # B
  6. print(max(zip(max_info.values(), max_info.keys()))) # (222, "B")

2.求n*n的二维数组的对角线之和

  1. def array_sum(list_info):
  2. """n*n的矩阵对角线的和"""
  3. num = 0
  4. for i in range(len(list_info)):
  5. for j in range(len(list_info)):
  6. array1 = list_info[i]
  7. array2 = array1[j]
  8. if i == j or i + j == len(list_info) - 1:
  9. print('i=', i, 'j=', j, 'array2=', array2)
  10. num += array2
  11. print(num)
  12. array_sum([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

3.倒水问题

  1. little_cup = int(input("请输入小水杯容量:"))
  2. big_cup = int(input("请输入大水杯容量:"))
  3. target = int(input("请输入目标体积水容量:"))
  4. """
  5. 小杯不断往大杯中倒水
  6. 大杯满了大杯全部倒掉
  7. 小杯继续往大杯倒水,直到得到目标水量,或者得不到目标水量退出循环
  8. """
  9. i = 2
  10. while True:
  11. if little_cup < big_cup:
  12. first_result = little_cup % big_cup
  13. if first_result == target:
  14. print("得到目标水量:{}".format(first_result))
  15. break
  16. elif target < big_cup:
  17. result = (little_cup * i) % big_cup
  18. i += 1
  19. if result == target:
  20. print("已经成功得到目标水量:{}".format(result))
  21. break
  22. elif result == first_result:
  23. print("无法得到目标水量")
  24. break

4.找出列表中出现频率最高的元素

  1. from collections import Counter
  2. """1613. 最高频率的IP
  3. 给定一个字符串数组lines, 每一个元素代表一个IP地址,找到出现频率最高的IP。
  4. 样例2:
  5. 输入 = ["192.168.1.1","192.118.2.1","192.168.1.1","192.118.2.1","192.118.2.1"]
  6. 输出 "192.118.2.1"
  7. 注意事项
  8. 给定数据只有一个频率最高的IP"""
  9. class Solution:
  10. def highest_Frequency(self, iplines):
  11. # return Counter(iplines).most_common()[0][0] # 方法1
  12. # dict1 = {}
  13. # for key in iplines:
  14. # dict1[key] = dict1.get(key, 0)+1
  15. # return max(dict1.keys(), key=lambda x: x[1]) #方法2
  16. ans = iplines[0]
  17. mapdic = {} # 记录每个ip出现的次数
  18. for ip in iplines:
  19. if ip in mapdic:
  20. mapdic[ip] += 1
  21. # print("mapdic:{}".format(mapdic))
  22. else:
  23. mapdic[ip] = 1
  24. max = 0
  25. # 遍历出出现次数最大
  26. for key in mapdic:
  27. if int(mapdic[key]) > max:
  28. # 如果大于最大次数,则替换
  29. max = mapdic[key]
  30. key = ans
  31. return ans
  32. print(Solution().highest_Frequency(
  33. ["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"]))
  34. print(Solution().highest_Frequency(["192.168.1.1", "192.118.2.1", "192.168.1.1"]))

找出列表中出现频率最高的元素

  1. a = [1, 3, 4, 5, 6, 6, 6 ,6, 6]
  2. # 方法一
  3. count_dict = {}
  4. for i in a:
  5. # 元素没有在字典时,初始化赋值
  6. if i not in count_dict:
  7. count_dict[i] = 1
  8. # 元素已在字典中,累加统计
  9. else:
  10. count_dict[i] += 1
  11. print(max(count_dict.keys()))
  12. # 方法二
  13. count_dict_j = {}
  14. for j in a:
  15. count_dict_j[j] = count_dict_j.get(j, 1) + 1
  16. print(max(count_dict_j.keys()))