Skip to content

Instantly share code, notes, and snippets.

@maraca
Created April 13, 2011 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraca/918579 to your computer and use it in GitHub Desktop.
Save maraca/918579 to your computer and use it in GitHub Desktop.
Generators in python
#!/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