Python好东西

最近研究了一下Python,觉得他这种问答式的界面特别适合学习编程,下面就举两个例子。
1.快速排序的算法描述
>>> def qsort(aL):
...  if aL==[]:return []
...  else:
...   smaller=[x for x in aL[1:] if x<aL[0]] #比aL[0]小的部分
...   bigger=[x for x in aL[1:] if x>=aL[0]] #比aL[0]大(或相等)的部分
...   return qsort(smaller)+[aL[0]]+qsort(bigger)
...
>>> qsort([3,4,5,1])
[1, 3, 4, 5]
>>> import random
>>> a=range(0,100)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> random.shuffle(a)
>>> a
[69, 77, 17, 97, 21, 1, 44, 20, 82, 46, 59, 63, 4, 47, 38, 25, 48, 84, 72, 2, 52, 10, 31, 3, 58, 43, 9, 96, 95, 27, 0, 71, 40, 12, 76, 8, 14, 79, 53, 80, 28, 15, 91, 22, 65, 68, 86, 18, 32, 85, 55, 36, 92, 74, 50, 11, 83, 81, 7, 57, 90, 54, 87, 24, 29, 37, 61, 35, 56, 60, 88, 75, 30, 16, 13, 39, 26, 70, 93, 49, 51, 23, 41, 98, 66, 99, 89, 5, 34, 6, 94, 64, 67, 62, 78, 73, 19, 33, 42, 45]
>>> qsort(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

注:算法效率虽然不高,但意思很明朗。
2.模仿QQ尾巴之“记事本尾巴”
用到了的“Hook”,需要下载一个pyHook 模块
import win32ui,win32con,pyHook,pythoncom
def hookhandle(event):
    if event.KeyID==13:  #捕捉回车键(注,QQ尾巴捕捉Ctrl+Enter及单击发送按钮)
 try:
         pwin=win32ui.FindWindow('Notepad',None) #找到记事本窗口
         textbox=win32ui.FindWindowEx(pwin,None,'Edit',None) #找到编辑窗口
         buf='0x0'*1024
         oldlen=textbox.SendMessage(win32con.WM_GETTEXT,buf) #获得编辑窗口中原有的文本
         textbox.SendMessage(win32con.WM_SETTEXT,buf[0:oldlen]+'\r\nhttp://www.csdn.net') #加上个尾巴,呵呵
 except:
  pass
hm = pyHook.HookManager()  #钩子实例化
hm.KeyDown=hookhandle  #指明回调函数
hm.HookKeyboard()   #Hook键盘
pythoncom.PumpMessages()  #消息循环

当然,QQ尾巴肯定不会用动态语言写,我在这里只是为了说明python的确是一个很好的学习工具,只要你能想到原理,
那么赶紧用python验证一下吧.

你可能感兴趣的:(python)