众所周知,Python是个非常强大的语言,可以用一行代码来做很多事情。本次活动我们将向大家展示和教授一行代码搞定事情。
主题内容如下:
1 Python一行代码大展示活动,介绍很多的用一行代码做各种事情的例子,给大家展示神奇的Python。大家可以轻松学会Python的精妙。
2 分享CodeJam 2013大赛中的几个题目的Python实现。
预计参加人数:30人
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
print map(lambda x: x * 2, range(1,11))
2. Sum a List of Numbers
print sum(range(1,1001))
3. Verify if Exists in a String
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
print open("ten_one_liners.py").readlines()
5. Happy Birthday to You!
print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear
Name"),range(4))
6. Filter list of numbers
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
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
print min([14, 35, -7, 46, 98])
print max([14, 35, -7, 46, 98])
9. Parallel Processing
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.
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))))
|