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
printmap(lambdax:x*2,range(1,11))
2. Sum a List of Numbers
1
printsum(range(1,1001))
3. Verify if Exists in a String
1234
wordlist=["scala","akka","play framework","sbt","typesafe"]tweet="This is an example tweet talking about scala and sbt."printmap(lambdax:xintweet.split(),wordlist)
4. Read in a File
1
printopen("ten_one_liners.py").readlines()
5. Happy Birthday to You!
1
printmap(lambdax:"Happy Birthday to "+("you"ifx!=2else"dear Name"),range(4))
fromxml.dom.minidomimportparse,parseStringimporturllib2# note - i convert it back into xml to pretty print itprintparse(urllib2.urlopen("http://search.twitter.com/search.atom?&q=python")).toprettyxml(encoding="utf-8")
10. Sieve of Eratosthenes
There is no Sieve of Eratosthenes operator, but that is hardly a constraint.
123
n=50# We want to find prime numbers between 2 and 50printsorted(set(range(2,n+1)).difference(set((p*f)forpinrange(2,int(n**0.5)+2)forfinrange(2,(n/p)+1))))