一些迭代器实用程序

dm.iter的Python项目详细描述


迭代器实用程序的一个小集合。

目前,有一个与关系相关的单一效用族。

关系实用程序

这些实用程序在dm.iter.relation中实现。

关系由元素到 其直接相关元素的迭代器。 映射或者是具有__getitem__方法的对象, 未定义的可调用的引发ValueError。 输入参数或支持订阅的对象。 必须允许元素作为集合元素。

可用的实用程序有depth_first_searchbreath_first_search。 它们将关系和元素迭代器“根”作为参数 并为“根”生成关系的传递闭包 深度优先或呼吸优先。

让我们看一个小例子。我们的关系是 0和11作为域并将元素映射到该元素的三倍。

>>> def relation(x):
...   if not (isinstance(x, int) and 0 <= x < 11): raise ValueError
...   return (3 * x,)
...
>>> from dm.iter.relation import depth_first_search, breadth_first_search
>>> tuple(depth_first_search(relation, ()))
()
>>> tuple(breadth_first_search(relation, ()))
()
>>> tuple(depth_first_search(relation, (1, 2, 3)))
(1, 3, 9, 27, 2, 6, 18)
>>> tuple(breadth_first_search(relation, (1, 2, 3)))
(1, 2, 3, 6, 9, 18, 27)
>>> dfs = depth_first_search(relation, (1, 2, 3))
>>> dfs.next()
1
>>> dfs.next()
3

现在让我们的关系映射x(2*x, 3*x)

>>> def relation(x):
...   if not (isinstance(x, int) and 0 <= x < 11): raise ValueError
...   return (2 * x, 3 * x)
...
>>> tuple(depth_first_search(relation, (1,)))
(1, 2, 4, 8, 16, 24, 12, 6, 18, 3, 9, 27)
>>> tuple(breadth_first_search(relation, (1,)))
(1, 2, 3, 4, 6, 9, 8, 12, 18, 27, 16, 24)

关系也可以由字典指定。

>>> relation = dict((i, (2*i, 3*i)) for i in range(11))
>>> tuple(depth_first_search(relation, (1,)))
(1, 2, 4, 8, 16, 24, 12, 6, 18, 3, 9, 27)
>>> tuple(breadth_first_search(relation, (1,)))
(1, 2, 3, 4, 6, 9, 8, 12, 18, 27, 16, 24)

或者具有__getitem__方法的对象:

>>> from UserDict import UserDict
>>> relation = UserDict(relation)
>>> tuple(depth_first_search(relation, (1,)))
(1, 2, 4, 8, 16, 24, 12, 6, 18, 3, 9, 27)
>>> tuple(breadth_first_search(relation, (1,)))
(1, 2, 3, 4, 6, 9, 8, 12, 18, 27, 16, 24)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java Oracle将休眠为ISO 8601日期格式   当有线程时,swing计时器不会停止。睡在Java里面   如何使用swing在java中清空密码字段值(字符串)   如何在编辑文本字段上设置单词java(安卓)   单独类中的java OkHttp请求   java Tomcat配置文件/上下文xml似乎已经崩溃了。请确保它是可分析和有效的。有关详细信息,请参阅服务器日志   java在科尔多瓦的ActivityResult上传递   java如何在映射中保持插入顺序。工厂?   “DataOutputStream”和“ObjectOutputStream”之间的java差异   java从FTP文件列表中获取项目的时间戳   java如何在spring security中为每个人忽略一些资源/URL?   模板类嵌套时新的Java泛型类构造函数问题   java读取并查找文件大小为1GB的行   java如何使用字符串say“stop”停止整数格式的while循环   java是否可以在应用程序启动之间将JVM保留在内存中?   java Springboot出现“出现意外错误(类型=内部服务器错误,状态=500)”的问题