python的確是個好工具

來源:互聯網
上載者:User

最近研究了一下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驗證一下吧.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.