Skip to content

Instantly share code, notes, and snippets.

@andreburgaud
Last active August 29, 2015 14:08
Show Gist options
  • Save andreburgaud/7d961e558098127e870d to your computer and use it in GitHub Desktop.
Save andreburgaud/7d961e558098127e870d to your computer and use it in GitHub Desktop.
List comprehensions in Python. Translation from book "Programming Haskell" examples. Erik Meijer Functional Programming class on Edx.
pairs = lambda xs: zip(xs, xs[1:])
print pairs([1,2,3,4,5,6]) # [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
sorted = lambda xs: all([x<=y for (x, y) in pairs(xs)])
print sorted([1,2,3,4,5,6,7]) # True
print sorted([1,2,3,4,5,9,7]) # False
print "- Factors of an integer- "
factors = lambda n: [ x for x in range(1,n+1) if n % x == 0 ]
x = 15
print "Factors of %d: %r" % (x, factors(x))
x = 7
print "Factors of %d: %r\n" % (x, factors(x))
print "- Is a number a prime? -"
prime = lambda n: factors(n) == [1,n]
x = 15
print "Is %d a prime? %r" % (x, prime(x))
x = 7
print "Is %d a prime? %r\n" % (x, prime(x))
print "- List all the primes less than a given number -"
primes = lambda n: [ x for x in range(2, n+1) if prime(x) ]
x = 7
print "Primes up to %d: %r" % (x, primes(x))
x = 40
print "Primes up to %d: %r" % (x, primes(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment