Created
April 13, 2011 22:35
-
-
Save maraca/918579 to your computer and use it in GitHub Desktop.
Generators in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python2.6 | |
import random | |
# yields a random customer id | |
def random_generator(percentage): | |
for customer in xrange(1000000): | |
if random.randrange(0, 100, 1) < percentage: | |
yield customer | |
# generates a bunch of random user ids and unpaid customers | |
customers = (customer for customer in random_generator(70)) | |
unpaid_customers = (unpaid for unpaid in random_generator(10)) | |
# parse by only looking at first item of unpaid customers | |
# O(1) vs O(n) for unpaid_customers | |
# O(n) vs O(n2) for global lookup | |
# does not load the whole list in memory | |
match = 0 | |
current_id = -1 | |
for customer_id in customers: | |
if unpaid_customers: | |
if customer_id >= current_id: | |
try: | |
current_id = unpaid_customers.next() | |
except StopIteration, error: | |
break | |
if customer_id == current_id: | |
match += 1 | |
print '%d matches.' % match |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment