/code/blog

Code, code and code

10 Python One Liners to Impress Your Friends

After 10 Scala / Ruby / Clojure / CoffeeScript one liners to impress your friends, i thought it might be interesting to quickly try out the same in Python too. Without much ado.. here goes. Note that the variable declarations and imports are on separate lines as necessary. Also every line is written so as to print out the results to stdout for quick verification For what it is worth, this hardly took any time - this post is probably one of the quickest I have written.

1. Multiple Each Item in a List by 2

1
print map(lambda x: x * 2, range(1,11))
2. Sum a List of Numbers
1
print sum(range(1,1001))
3. Verify if Exists in a String
1
2
3
4
wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"]
tweet = "This is an example tweet talking about scala and sbt."

print map(lambda x: x in tweet.split(),wordlist)
4. Read in a File
1
print open("ten_one_liners.py").readlines()
5. Happy Birthday to You!
1
print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"),range(4))
6. Filter list of numbers
1
print reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
7. Fetch and Parse an XML web service
1
2
3
4
from xml.dom.minidom import parse, parseString
import urllib2
# note - i convert it back into xml to pretty print it
print parse(urllib2.urlopen("http://search.twitter.com/search.atom?&q=python")).toprettyxml(encoding="utf-8")
8. Find minimum (or maximum) in a List
1
2
print min([14, 35, -7, 46, 98])
print max([14, 35, -7, 46, 98])
9. Parallel Processing
1
2
3
4
import multiprocessing
import math

print list(multiprocessing.Pool(processes=4).map(math.exp,range(1,11)))
10. Sieve of Eratosthenes There is no Sieve of Eratosthenes operator, but that is hardly a constraint.
1
2
3
n = 50 # We want to find prime numbers between 2 and 50

print sorted(set(range(2,n+1)).difference(set((p * f) for p in range(2,int(n**0.5) + 2) for f in range(2,(n/p)+1))))

Comments