一些迭代器实用程序

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我能在这个程序中更好地使用内存吗?   为什么我的Java while循环迭代了一半   java IntelliJ IDEA不在构建时复制资源   socket仅在Java TCP服务器输出上检查客户端断开连接   java游戏物理摩擦   java片段onClick调用方法   symja数学分析器中无法识别java Abs[x]   java在使用泛型时创建二进制搜索树类的实例?   java在外键约束表上的添加和删除   语法java表达式的含义,如果有条件   java创建内联对象并作为参数传递   是否有相当于Redis排序集(zset)的Java数据结构   java找不到适合的方法(无参数)   音频文件操作给定字节帧的音量Java   Eclipse4不以JavaWebStart启动   java如何使用org在JSON对象中获取嵌套的键元素。json?   java与Jackson的反序列化:“org.codehaus.Jackson.map.JsonMappingException:无法反序列化[projectname]的实例。”   字符串的Java正则表达式   spring集成上的java检测缺火指令