Python Generator Code Application Examples

Source: Internet
Author: User
Keywords python generator python generator application
In writing the program, we should pay attention to summarizing some common techniques, such as List Comprehensions, Dict Comprehensions, and other previous ways to improve efficiency.

In generator, a very common usage is the use of yield. Every time the next() function of the generator is called, the execution will start from the last yield statement executed.

Sometimes, we have to find a "combination" of numbers that satisfy "a certain condition" in a set of "given numbers". What should we do?

To be more specific, for example, if we want to find a combination of two numbers with a sum of 50 from the numbers 1 to 100, how to solve it? My code is given below:

# coding:utf-8
a = [i for i in xrange(100)]
b = {i+1:True for i in a}
print b
def fun(integer):
    for i in xrange(100):
        for j in xrange(i+1, 100):
            if b.get(i) and b.get(j) and i+j==integer:
                yield i, j
integer = 50
obj = fun(integer) # generator
while 1: # while 1 is faster than while True
    try:
        print obj.next()
    except Exception as e:
        print e
        break

Similarly, when we want to find a combination of three and three numbers with a sum of 50 from 1 to 100, we can use the following code:

# coding:utf-8
a = [i for i in xrange(100)]
b = {i+1:True for i in a}
print b
def fun(integer):
    for i in xrange(100):
        for j in xrange(i+1, 100):
            for k in xrange(j+1, 100):
                if b.get(i) and b.get(j) and b.get(k) and i+j+k==integer:
                    yield i, j, k
integer = 50
obj = fun(integer) # generator
while 1: # while 1 is faster than while True
    try:
        print obj.next()
    except Exception as e:
        print e
        break

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.