one simple example of yield

Write a generator that returns every arrangement of items such that each is in one or none of two different bags.

Each combination should be given as a tuple of two lists, the first being the items in bag1, and the second being the items in bag2.


def yieldAllCombos(items):
    N = len(items)
    
    for i in xrange(3**N):
        bag1 = []
        bag2 = []
        for j in xrange(N):
            # test bit jth of integer i
            if (i/3**j) % 3 == 1:
                bag1.append(items[j])
            if  (i/3**j) % 3 == 2:
                bag2.append(items[j])
        yield (bag1,bag2)

items = [1,7,3]
k=0
for i in yieldAllCombos(items):
    print i
    k+=1
print k

result was printed as following:
([], [])
([1], [])
([], [1])
([7], [])
([1, 7], [])
([7], [1])
([], [7])
([1], [7])
([], [1, 7])
([3], [])
([1, 3], [])
([3], [1])
([7, 3], [])
([1, 7, 3], [])
([7, 3], [1])
([3], [7])
([1, 3], [7])
([3], [1, 7])
([], [3])
([1], [3])
([], [1, 3])
([7], [3])
([1, 7], [3])
([7], [1, 3])
([], [7, 3])
([1], [7, 3])
([], [1, 7, 3])
27





全部评论

相关推荐

02-21 23:34
已编辑
厦门大学 Java
神哥不得了:神哥来啦~首先你的bg的话应该算是很好的了,可以把其他删掉,不需要手搓项目呀,直接找网上的项目看懂就行,第一个项目的话虽然和JAVA没有关系,但是他的星数很多,说明你的编程能力还是很强的,我觉得第一个项目是可以放上去的,但是第二个项目的话建议还是再换一个高质量的项目,感觉如果你再把高频top 50的八股再巩固几遍,完全有机会在没有实习的情况下,从暑期实习的大厂,机会还是很大的,注意别看一些假高频八股就行
点赞 评论 收藏
分享
人生一梦:24年我投暑期实习,它以我不是女的为理由拒绝了我查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务