当前位置:   article > 正文

Python-VBA函数之旅-set函数

Python-VBA函数之旅-set函数

目录

一、set函数的常见应用场景:

二、set函数使用注意事项

三、如何用好set函数?

1、set函数:

1-1、Python:

1-2、VBA:

2、推荐阅读:

个人主页: https://blog.csdn.net/ygb_1024?spm=1010.2135.3001.5421

一、set函数的常见应用场景:

        在Python中,set()函数用于创建一个无序且不包含重复元素的集合,由于其独特的性质,set()函数在许多实际场景中都非常有用,常见的应用场景有:

1、去重:当你有一个列表或其他可迭代对象,并且你想快速去除其中的重复元素时,可以使用 set()函数。

2、快速查找:由于set的实现基于哈希表,因此它提供了平均时间复杂度为O(1)的成员查找操作(即 `in` 关键字),这在需要快速检查元素是否存在于集合中时非常有用。

3、集合运算:集合支持多种集合运算,如并集(|)、交集(&)、差集(-)和对称差集(^),这些运算在数据分析、算法实现等领域非常有用。

4、过滤和选择:结合列表推导式,可以使用集合来过滤和选择数据。

5、字典键去重:由于集合中的元素是唯一的,因此它们经常被用作字典的键来确保键的唯一性。

6、性能优化:在某些需要快速查找或判断元素是否存在的场景中,使用集合通常比使用列表更快,因为集合在内部使用哈希表实现,提供了快速的查找和插入操作。

7、图形和网络算法:在处理图形和网络问题时,set常常用于表示节点或边的集合,并进行诸如查找连接节点、计算共同邻居等操作。

8、数据清洗和预处理:在数据清洗和预处理阶段,集合可以用于快速识别并去除重复的数据项。

9、缓存和状态管理:在某些情况下,你可能需要跟踪一个对象或一组对象的状态或属性,使用set()函数可以轻松地存储这些状态,并在需要时进行检查或更新。

10、实现集合的幂集:集合的幂集是所有可能的子集(包括空集和原集合本身)的集合。

二、set函数使用注意事项

        在Python中,set()是一个内置的数据类型,用于存储无序且不重复的元素集合。虽然set()本身不是一个函数(它是一个类,用于创建集合对象),但了解其使用方式和注意事项对于有效使用集合是非常重要的。以下是使用set()(或集合)时的一些注意事项:

1、无序性:集合是无序的,因此你不能依赖元素在集合中的插入顺序。
2、不可变性:集合中的元素必须是不可变类型(如整数、浮点数、字符串、元组等),但集合本身是可变的。
3、去重性:集合会自动去除重复的元素,如果你尝试向集合中添加一个已经存在的元素,该操作不会有任何效果。
4、不支持索引:由于集合是无序的,因此它不支持索引或切片操作。
5、运算符支持:集合支持多种集合运算符,如并集(|)、交集(&)、差集(-)和对称差集(^)。
6、迭代:你可以遍历集合中的所有元素。
7、添加和删除:你可以使用add()方法向集合中添加元素,使用remove()或discard()方法删除元素,如果尝试删除的元素不存在于集合中,remove()会引发KeyError异常,而discard()则不会。
8、性能:集合的查找、添加和删除操作通常具有平均时间复杂度为O(1)的性能,这是因为集合在内存中是通过哈希表实现的。
9、转换:你可以将其他可迭代对象(如列表、元组或字符串)转换为集合,以去除其中的重复元素,但要注意,这样做会丢失原始顺序。
10、空集合的创建:要创建一个空集合,你不能只使用{},因为这会创建一个空字典;相反,你应该使用set()或{}后跟一个逗号来创建空集合(例如set() 或{}),但在实践中,通常只使用set()。
11、子集和超集:你可以使用 `<`、`<=`、`>` 和 `>=` 运算符来检查一个集合是否是另一个集合的子集或超集。
12、不可哈希类型:集合不能包含列表或其他可变类型作为元素,因为这些类型是不可哈希的,如果你尝试这样做,Python会抛出一个TypeError异常。
13、冻结集合:如果你需要一个不可变的集合(即其元素在创建后不能更改),可以使用 frozenset()函数来创建一个冻结集合。

三、如何用好set函数?

        在Python中,set()不是一个函数,而是一个内置的数据类型,用于创建集合对象集合(set)是一个无序且不包含重复元素的数据集合,要充分利用Python的集合(set),需遵循以下建议:

1、去重:集合的一个主要优点是它们会自动去除重复的元素,如果你有一个列表或其他可迭代对象,并且想要去除其中的重复项,你可以将其转换为集合。

2、集合运算:集合支持多种集合运算,如并集、交集、差集和对称差集。

3、检查元素是否存在:使用 `in` 关键字可以检查一个元素是否存在于集合中。

4、添加和删除元素:使用add()方法向集合中添加元素,使用remove()或discard()方法删除元素。

5、集合的交集更新:如果你想要更新一个集合,使其只包含与另一个集合的交集,可以使用intersection_update()方法。

6、集合的差集更新:类似地,你可以使用difference_update()方法来更新一个集合,使其只包含与另一个集合的差集。

7、判断子集和超集:使用 `<`、`<=`、`>` 和 `>=` 运算符来判断一个集合是否是另一个集合的子集或超集。

8、不可变集合:如果你需要一个不可变的集合(即其内容在创建后不能更改),可以使用 frozenset(),这在需要将集合作为字典的键或其他需要不可变类型的地方时很有用。

9、注意性能:集合的查找、添加和删除操作通常具有平均时间复杂度为O(1)的性能,因为它们是通过哈希表实现的,这使得集合在处理大型数据集时特别有效。

10、小心使用可变元素:集合中的元素必须是不可变的,如果你尝试将一个可变对象(如列表)添加到集合中,Python会抛出一个TypeError异常。

1、set函数
1-1、Python:
  1. # 1.函数:set
  2. # 2.功能:用于将可迭代对象转换为一个无序且无重复元素的可变集合
  3. # 3.语法:set([iterable])
  4. # 4.参数:iterable,表示要转换为集合的可迭代对象,可以是列表、元组、range对象、字符串等
  5. # 5.返回值:
  6. # 5-1、无参形式:返回一个新的空集合
  7. # 5-2、有参形式:返回一个新的集合对象
  8. # 6.说明:
  9. # 7.示例:
  10. # 用dir()函数获取该函数内置的属性和方法
  11. print(dir(set))
  12. # ['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
  13. # '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__',
  14. # '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__',
  15. # '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
  16. # '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection',
  17. # 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
  18. # 用help()函数获取该函数的文档信息
  19. help(set)
  20. # 应用一:去重
  21. # 示例1: 去除列表中的重复项
  22. # 原始列表包含重复项
  23. original_list = [1, 2, 2, 3, 4, 4, 5, 5, 5]
  24. # 使用set()去除重复项,然后转回列表
  25. unique_list = list(set(original_list))
  26. # 注意:set是无序的,因此转换回列表后顺序可能会改变
  27. print(unique_list) # 输出可能是 [1, 2, 3, 4, 5],但顺序不一定
  28. # 如果需要保持原始顺序,可以使用其他方法,如列表推导式和if语句
  29. unique_list_ordered = []
  30. [unique_list_ordered.append(item) for item in original_list if item not in unique_list_ordered]
  31. print(unique_list_ordered) # 输出将保持原始顺序
  32. # [1, 2, 3, 4, 5]
  33. # [1, 2, 3, 4, 5]
  34. # 示例2: 去除字符串中的重复字符
  35. # 原始字符串包含重复字符
  36. original_string = "Hello, Python!"
  37. # 使用set()去除重复字符,但set不能直接转回字符串
  38. unique_chars = set(original_string)
  39. # 如果需要将结果转换回字符串,并去除顺序的影响(因为set是无序的)
  40. unique_string = ''.join(sorted(unique_chars))
  41. print(unique_string)
  42. # !, HPehlnoty
  43. # 示例3: 去除嵌套列表中的重复子列表(注意:set不能直接处理列表作为元素)
  44. # 原始嵌套列表包含重复子列表
  45. original_nested_list = [[1, 2], [3, 4], [1, 2], [5, 6]]
  46. # 使用tuple()转换子列表为元组,并使用set()去除重复项
  47. unique_nested_set = set(map(tuple, original_nested_list))
  48. # 转换回列表(但子列表将变为元组)
  49. unique_nested_list_tuples = list(unique_nested_set)
  50. # 如果需要子列表仍为列表而不是元组,则再次转换
  51. unique_nested_list = [list(item) for item in unique_nested_list_tuples]
  52. print(unique_nested_list)
  53. # [[1, 2], [3, 4], [5, 6]]
  54. # 应用二:快速查找
  55. # 示例1: 查找元素是否在集合中
  56. # 创建一个集合
  57. my_set = {3, 5, 6, 8, 10, 11, 24}
  58. # 查找元素
  59. element_to_find = 10
  60. if element_to_find in my_set:
  61. print(f"{element_to_find} 在集合中")
  62. else:
  63. print(f"{element_to_find} 不在集合中")
  64. # 查找不存在的元素
  65. element_not_found = 7
  66. if element_not_found in my_set:
  67. print(f"{element_not_found} 在集合中")
  68. else:
  69. print(f"{element_not_found} 不在集合中")
  70. # 10 在集合中
  71. # 7 不在集合中
  72. # 示例2: 使用集合进行快速去重和查找
  73. # 原始列表包含重复元素
  74. original_list = [1, 2, 2, 3, 4, 4, 5, 5, 5]
  75. # 使用集合去重
  76. unique_set = set(original_list)
  77. # 查找元素
  78. element_to_find = 4
  79. if element_to_find in unique_set:
  80. print(f"{element_to_find} 在去重后的集合中")
  81. else:
  82. print(f"{element_to_find} 不在去重后的集合中")
  83. # 如果你想将结果转换回列表(但不保证顺序)
  84. unique_list = list(unique_set)
  85. print(unique_list)
  86. # 4 在去重后的集合中
  87. # [1, 2, 3, 4, 5]
  88. # 示例3: 查找两个集合的交集
  89. # 创建两个集合
  90. set1 = {1, 2, 3, 4, 5}
  91. set2 = {4, 5, 6, 7, 8}
  92. # 查找交集
  93. intersection = set1 & set2
  94. print(intersection)
  95. # 查找一个元素是否在两个集合的交集中
  96. element_to_check = 4
  97. if element_to_check in intersection:
  98. print(f"{element_to_check} 在两个集合的交集中")
  99. else:
  100. print(f"{element_to_check} 不在两个集合的交集中")
  101. # {4, 5}
  102. # 4 在两个集合的交集中
  103. # 应用三:集合运算
  104. # 示例1: 并集(Union)
  105. # 创建两个集合
  106. set1 = {1, 2, 3, 4}
  107. set2 = {3, 4, 5, 6}
  108. # 使用 | 运算符计算并集
  109. union_set = set1 | set2
  110. print(union_set)
  111. # {1, 2, 3, 4, 5, 6}
  112. # 示例2: 交集(Intersection)
  113. # 创建两个集合
  114. set1 = {1, 2, 3, 4}
  115. set2 = {3, 4, 5, 6}
  116. # 使用 & 运算符计算交集
  117. intersection_set = set1 & set2
  118. print(intersection_set)
  119. # {3, 4}
  120. # 示例3: 差集(Difference)
  121. # 创建两个集合
  122. set1 = {1, 2, 3, 4}
  123. set2 = {3, 4, 5, 6}
  124. # 使用 - 运算符计算差集(set1中有但set2中没有的元素)
  125. difference_set = set1 - set2
  126. print(difference_set)
  127. # 反过来计算差集(set2中有但set1中没有的元素)
  128. difference_set_reverse = set2 - set1
  129. print(difference_set_reverse)
  130. # {1, 2}
  131. # {5, 6}
  132. # 示例4: 对称差集(Symmetric Difference)
  133. # 创建两个集合
  134. set1 = {1, 2, 3, 4}
  135. set2 = {3, 4, 5, 6}
  136. # 使用 ^ 运算符计算对称差集(存在于一个集合中但不同时存在于两个集合中的元素)
  137. symmetric_difference_set = set1 ^ set2
  138. print(symmetric_difference_set)
  139. # 示例5: 判断一个集合是否是另一个集合的子集(Subset)
  140. # 创建两个集合
  141. set1 = {1, 2, 3}
  142. set2 = {1, 2, 3, 4, 5}
  143. # 使用 <= 运算符判断set1是否是set2的子集
  144. is_subset = set1 <= set2
  145. print(is_subset)
  146. # 反过来判断set2是否是set1的子集
  147. is_subset_reverse = set2 <= set1
  148. print(is_subset_reverse)
  149. # True
  150. # False
  151. # 示例6: 判断两个集合是否有交集(Intersection)
  152. # 创建两个集合
  153. set1 = {1, 2, 3}
  154. set2 = {3, 4, 5}
  155. # 使用&运算符和if语句判断两个集合是否有交集
  156. has_intersection = bool(set1 & set2)
  157. print(has_intersection)
  158. # 如果没有交集
  159. set3 = {6, 7, 8}
  160. has_intersection_no = bool(set1 & set3)
  161. print(has_intersection_no)
  162. # True
  163. # False
  164. # 应用四:过滤和选择
  165. # 示例1: 使用集合过滤列表中的重复项
  166. # 原始列表包含重复项
  167. original_list = [1, 2, 2, 3, 4, 4, 5, 5, 5]
  168. # 使用集合去重,然后转回列表
  169. filtered_list = list(set(original_list))
  170. # 注意:集合是无序的,因此转换回列表后顺序可能会改变
  171. print(filtered_list)
  172. # [1, 2, 3, 4, 5]
  173. # 示例2: 使用集合选择两个列表中共有的元素
  174. # 两个列表
  175. list1 = [1, 2, 3, 4, 5]
  176. list2 = [4, 5, 6, 7, 8]
  177. # 将列表转换为集合
  178. set1 = set(list1)
  179. set2 = set(list2)
  180. # 使用集合的交集运算来选择共有的元素
  181. common_elements = set1 & set2
  182. # 如果需要结果是一个列表
  183. common_elements_list = list(common_elements)
  184. print(common_elements_list)
  185. # [4, 5]
  186. # 示例3: 使用集合过滤列表中的元素,只保留特定集合中的元素
  187. # 原始列表
  188. original_list = [1, 2, 3, 4, 5, 6]
  189. # 我们要保留的元素的集合
  190. selected_elements = {2, 4, 6}
  191. # 使用列表推导式来过滤列表,只保留在selected_elements中的元素
  192. filtered_list = [element for element in original_list if element in selected_elements]
  193. print(filtered_list)
  194. # [2, 4, 6]
  195. # 示例4: 使用集合的差集运算来过滤列表中的元素
  196. # 原始列表
  197. original_list = [1, 2, 3, 4, 5]
  198. # 我们想要从列表中移除的元素的集合
  199. elements_to_remove = {2, 4}
  200. # 将列表转换为集合
  201. set_original = set(original_list)
  202. # 使用差集运算来移除元素
  203. filtered_set = set_original - elements_to_remove
  204. # 如果需要结果是一个列表
  205. filtered_list = list(filtered_set)
  206. print(filtered_list)
  207. # [1, 3, 5]
  208. # 应用五:字典键去重
  209. # 假设我们有一个包含可能重复键的列表
  210. keys_with_duplicates = ['a', 'b', 'a', 'c', 'b', 'd']
  211. # 使用集合去除重复的键
  212. unique_keys = set(keys_with_duplicates)
  213. # 将去重后的键转换为一个字典,这里我们使用一个简单的值(比如None或者一个固定的值)
  214. # 如果你想为每个键分配一个特定的值,你需要有一个与键对应的值列表
  215. dict_with_unique_keys = {key: None for key in unique_keys}
  216. # 输出结果
  217. print(dict_with_unique_keys)
  218. values = [1, 2, 3, 4] # 注意:这个列表的长度应该与unique_keys的长度相同
  219. # 你可以使用zip函数来配对键和值(但你需要确保列表长度匹配)
  220. # 在这个例子中,我们假设values列表已经按照某种逻辑与unique_keys匹配
  221. # (在实际应用中,你可能需要根据具体的逻辑来配对键和值)
  222. dict_with_paired_values = dict(zip(unique_keys, values))
  223. # 输出结果(注意:如果values列表长度不够,将会丢失一些键)
  224. print(dict_with_paired_values)
  225. # {'a': None, 'd': None, 'b': None, 'c': None}
  226. # {'a': 1, 'd': 2, 'b': 3, 'c': 4}
  227. # 应用六:性能优化
  228. # 示例1: 使用集合进行高效的成员资格检查
  229. import time
  230. # 使用列表进行成员资格检查
  231. lst = list(range(1000000)) # 创建一个包含一百万个元素的列表
  232. element = 999999
  233. start_time = time.time()
  234. if element in lst:
  235. print("Element found in list.")
  236. print(f"List membership check took {time.time() - start_time} seconds.")
  237. # 使用集合进行成员资格检查
  238. set_lst = set(lst) # 将列表转换为集合
  239. start_time = time.time()
  240. if element in set_lst:
  241. print("Element found in set.")
  242. print(f"Set membership check took {time.time() - start_time} seconds.")
  243. # 注意到集合的成员资格检查速度更快
  244. # Element found in list.
  245. # List membership check took 0.013991117477416992 seconds.
  246. # Element found in set.
  247. # Set membership check took 0.0 seconds.
  248. # 示例2: 使用集合进行高效的去重操作
  249. # 使用列表推导式和if条件进行去重(较慢)
  250. lst = [1, 2, 2, 3, 4, 4, 5, 5, 5]
  251. unique_lst = []
  252. for item in lst:
  253. if item not in unique_lst:
  254. unique_lst.append(item)
  255. # 使用集合进行去重(更快)
  256. set_lst = set(lst)
  257. unique_lst_from_set = list(set_lst)
  258. # 注意到使用集合去重更加简洁且高效
  259. # 示例3: 使用集合进行高效的交集、并集和差集运算
  260. # 创建两个集合
  261. set1 = {1, 2, 3, 4, 5}
  262. set2 = {4, 5, 6, 7, 8}
  263. # 计算交集
  264. intersection = set1 & set2
  265. print(intersection) # 输出: {4, 5}
  266. # 计算并集
  267. union = set1 | set2
  268. print(union) # 输出: {1, 2, 3, 4, 5, 6, 7, 8}
  269. # 计算差集(set1中有但set2中没有的元素)
  270. difference = set1 - set2
  271. print(difference) # 输出: {1, 2, 3}
  272. # 这些集合运算比使用列表进行类似操作更加高效
  273. # {4, 5}
  274. # {1, 2, 3, 4, 5, 6, 7, 8}
  275. # {1, 2, 3}
  276. # 应用七:图形和网络算法
  277. # 示例1: 使用集合表示无向图的邻接关系
  278. # 假设我们有一个无向图,用字典表示邻接关系
  279. graph = {
  280. 'A': {'B', 'C'},
  281. 'B': {'A', 'D', 'E'},
  282. 'C': {'A', 'F'},
  283. 'D': {'B'},
  284. 'E': {'B', 'F'},
  285. 'F': {'C', 'E'},
  286. }
  287. # 我们可以使用集合来快速查找一个顶点的所有邻居
  288. def get_neighbors(graph, vertex):
  289. return graph[vertex]
  290. # 示例:查找顶点'B'的所有邻居
  291. print(get_neighbors(graph, 'B')) # 输出: {'A', 'D', 'E'}
  292. # 查找两个顶点之间是否有边(直接相邻)
  293. def are_adjacent(graph, vertex1, vertex2):
  294. return vertex2 in graph[vertex1]
  295. # 示例:检查顶点'A'和'B'是否相邻
  296. print(are_adjacent(graph, 'A', 'B')) # 输出: True
  297. # {'A', 'D', 'E'}
  298. # True
  299. # 示例2: 使用集合进行网络中的社区检测
  300. # 假设我们有一些已知的社区
  301. communities = {
  302. 'community1': {'A', 'B', 'C'},
  303. 'community2': {'D', 'E', 'F'},
  304. }
  305. # 图的定义,节点到邻居的映射
  306. graph = {
  307. 'A': {'B', 'D'},
  308. 'B': {'A', 'C', 'E'},
  309. 'C': {'B'},
  310. 'D': {'A', 'E', 'F'},
  311. 'E': {'B', 'D', 'F'},
  312. 'F': {'D', 'E'},
  313. }
  314. # 我们可以使用集合运算来查找跨社区的边或进行其他分析
  315. def find_inter_community_edges(graph, communities):
  316. inter_edges = set()
  317. for community in communities.values():
  318. for vertex in community:
  319. for neighbor in graph[vertex]:
  320. if neighbor not in community:
  321. # 如果邻居不在同一个社区中,则添加这条边到跨社区边集合
  322. inter_edges.add((vertex, neighbor))
  323. return inter_edges
  324. # 示例:查找跨社区的边
  325. print(find_inter_community_edges(graph, communities)) # 输出跨社区的边集合
  326. # {('D', 'A'), ('B', 'E'), ('A', 'D'), ('E', 'B')}
  327. # 应用八:数据清洗和预处理
  328. # 示例1:去除列表中的重复项
  329. # 原始列表,包含重复项
  330. original_list = [1, 2, 3, 2, 4, 4, 5, 5, 6]
  331. # 使用set()去除重复项,然后转换回列表
  332. cleaned_list = list(set(original_list))
  333. # 注意:set()破坏了原始顺序,如果需要保持顺序,可以使用其他方法
  334. # 例如,使用列表推导式和 if 语句来保持顺序
  335. cleaned_list_ordered = []
  336. [cleaned_list_ordered.append(item) for item in original_list if item not in cleaned_list_ordered]
  337. print("原始列表:", original_list)
  338. print("使用set()去除重复项:", cleaned_list)
  339. print("保持顺序的列表:", cleaned_list_ordered)
  340. # 原始列表: [1, 2, 3, 2, 4, 4, 5, 5, 6]
  341. # 使用set()去除重复项: [1, 2, 3, 4, 5, 6]
  342. # 保持顺序的列表: [1, 2, 3, 4, 5, 6]
  343. # 示例2:查找两个列表的交集
  344. # 列表1
  345. list1 = [1, 2, 3, 4, 5]
  346. # 列表2
  347. list2 = [4, 5, 6, 7, 8]
  348. # 使用set()查找交集
  349. intersection = set(list1).intersection(set(list2))
  350. print("列表1和列表2的交集:", intersection)
  351. # 列表1和列表2的交集: {4, 5}
  352. # 示例3:查找两个列表的并集
  353. # 列表1
  354. list1 = [1, 2, 3, 4, 5]
  355. # 列表2
  356. list2 = [4, 5, 6, 7, 8]
  357. # 使用set()查找并集,但注意这只会返回不重复的元素
  358. union_without_duplicates = set(list1).union(set(list2))
  359. # 如果要包含重复项,则需要使用其他方法,例如列表推导式
  360. union_with_duplicates = list(set(list1)) + [x for x in list2 if x not in set(list1)]
  361. print("列表1和列表2的不重复并集:", union_without_duplicates)
  362. print("列表1和列表2的包含重复项的并集:", union_with_duplicates)
  363. # 列表1和列表2的不重复并集: {1, 2, 3, 4, 5, 6, 7, 8}
  364. # 列表1和列表2的包含重复项的并集: [1, 2, 3, 4, 5, 6, 7, 8]
  365. # 示例4:查找一个列表在另一个列表中的差集
  366. # 列表1
  367. list1 = [1, 2, 3, 4, 5]
  368. # 列表2
  369. list2 = [4, 5, 6, 7, 8]
  370. # 使用set()查找差集
  371. difference = set(list1).difference(set(list2))
  372. print("列表1在列表2中的差集:", difference)
  373. # 列表1在列表2中的差集: {1, 2, 3}
  374. # 应用九:缓存和状态管理
  375. # 示例1:使用set作为缓存
  376. def find_factors(n):
  377. """
  378. Find all factors of n and return them as a set.
  379. This function uses a cache to avoid recalculating factors for the same number.
  380. """
  381. cache = {} # 使用字典作为缓存,因为我们需要存储输入和输出
  382. def _find_factors_helper(n):
  383. if n in cache:
  384. return cache[n]
  385. factors = {i for i in range(1, int(n ** 0.5) + 1) if n % i == 0}
  386. factors.update({n // i for i in factors if i != n // i}) # 添加另一半因子
  387. cache[n] = factors
  388. return factors
  389. return _find_factors_helper(n)
  390. # 示例
  391. print(find_factors(12)) # 输出: {1, 2, 3, 4, 6, 12}
  392. print(find_factors(12)) # 再次调用,但使用缓存,所以计算会更快
  393. # {1, 2, 3, 4, 6, 12}
  394. # {1, 2, 3, 4, 6, 12}
  395. # 示例2:使用set进行状态管理
  396. # 初始化用户集合
  397. completed_users = set()
  398. def mark_task_completed(user_id):
  399. """
  400. 将用户标记为已完成任务
  401. """
  402. completed_users.add(user_id)
  403. print(f"User {user_id} has completed the task.")
  404. def check_task_status(user_id):
  405. """
  406. 检查用户是否已完成任务
  407. """
  408. if user_id in completed_users:
  409. return "Completed"
  410. else:
  411. return "Not Completed"
  412. # 示例
  413. mark_task_completed(123) # 输出: User 123 has completed the task.
  414. print(check_task_status(123)) # 输出: Completed
  415. print(check_task_status(456)) # 输出: Not Completed
  416. # User 123 has completed the task.
  417. # Completed
  418. # Not Completed
  419. # 应用十:实现集合的幂集
  420. def powerset(s):
  421. """
  422. Generate the powerset of a given set.
  423. :param s: The input set.
  424. :return: The powerset of the input set.
  425. """
  426. if not s:
  427. return [set()]
  428. subsets_without_current = powerset(s - {next(iter(s))})
  429. subsets_with_current = [s_ | {next(iter(s))} for s_ in subsets_without_current]
  430. return subsets_without_current + subsets_with_current
  431. # 示例
  432. input_set = {3, 5, 6, 8}
  433. power_set = powerset(input_set)
  434. for subset in power_set:
  435. print(subset)
  436. # set()
  437. # {6}
  438. # {5}
  439. # {5, 6}
  440. # {3}
  441. # {3, 6}
  442. # {3, 5}
  443. # {3, 5, 6}
  444. # {8}
  445. # {8, 6}
  446. # {8, 5}
  447. # {8, 5, 6}
  448. # {8, 3}
  449. # {8, 3, 6}
  450. # {8, 3, 5}
  451. # {8, 3, 5, 6}
1-2、VBA
略,待后补。
2、推荐阅读:

2-1、Python-VBA函数之旅-round()函数

Python算法之旅:Algorithm

Python函数之旅:Functions

个人主页: https://blog.csdn.net/ygb_1024?spm=1010.2135.3001.5421
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/674177
推荐阅读
相关标签
  

闽ICP备14008679号