新军's profileIns'PhotosBlogListsMore Tools Help

Blog


    August 01

    Python实现顺序查找

    #coding:utf-8
    #sequence search
    a = (1,2,3,4,6,7,89,0,43,67,89)
    print range(len(a))
    search = 89
    flag = 0
    for item in range(len(a)):
        if a[item] == search:
            flag = item + 1
    if flag != 0:
        print 'get,position is:',flag
    else:
        print 'not found'

    这个算法比较简单,代码就大家自己看吧

    Python实现二分查找

    下午对着二分查找得原理用python进行了模拟.

    越来越发现,python才是数据结构和算法表示的王者,c++表示过于复杂.

    python的简单明了现在全部体现出来了.

    代码如下:

    #coding:utf-8
    a = (1,2,3,4,56,80,900)
    search = 56
    low = 0
    high = len(a) - 1
    mid = (low + high) / 2
    i = 0
    flag = 0
    while(low <= high and flag == 0):
        i += 1
        if a[mid] == search:
            flag = mid 
            break
        if a[mid] > search:
            high = mid - 1
            mid = (low + high) / 2       
        else:
            low = mid + 1
            mid = (low + high) / 2
    if flag != 0:
        print 'got in ',flag
    else:
        print 'not found'

    print '共执行了',i,'次查找'

    写到这,讲个小技巧,php中echo的时候不要都用"."哦.要学python的print,用","分开,效率可是杠杠的

    终于全部看完Tkinter的教程

    已经了解了全部的Tkinter的内容,可以开始着手设计自己的UI界面的Python应用程序了.

    第一个应用程序暂定为EasCMS(PHP版)的桌面应用.目前正在写接口.

    第一次将PHP与Python结合起来了.

    对于这个胶水语言,暂时还没有将她与C++等粘合在一起,弄完这个项目之后好好试试.

    瞎扯

    最近一直在学习技术方面的东西,拼命的实践,写代码,积累项目经验,只是为了自己热爱的技术.

    终于有一天感觉有点累了.

    QQ for linux终于出来了.以后可以彻底的搬家了.再也不用回到windows的下面了.

    飞信linux版本的也搞到了,linux下的编程好好就是了.

    是时候该休息休息了.

    Tkinter设置root的大小,以及相对屏幕的位置

    from Tkinter import *

    root = Tk()

    root.geometry('300x300+100+300')

    #设置宽度和高度均为300,相对于屏幕左上角的坐标位置为(+100,+300)

    root.mainloop()

    July 31

    Tkinter中的Text

    在text中添加button

    from Tkinter import *

    root = Tk()

    def printMe():

        print 'I\'m in text'

    t = Text(root)

    for i in range(10)

        t.insert(1.0,'01234567890\n')

    b = Button(t, text = 'click me', command = printMe)

    t.window_create('2.0', window = b)

    t.pack()

    root.mainloop()

    July 26

    the usage of lambda

    lambda ,in my option,use it like inline functions in c++.

    maybe this is more simple.

    for it creats functions dynamic.

    like:

    f1 = lambda x,y : x ** y

    print f1(5,2)

    so simple,and also very powerful!

    Command Line Arguments with Python

    import sys

    if len(sys.argv) < 2:

        print u'input the argument like -h -r -s'

    for i in sys.argv[1:]:

        if i == '-h':

            showHelp()

        elif i == '-s':

            startService()

        else:

            showError()

    July 25

    Module Shelve

    shelve use dictionary for its persistent storage

    import shelve

    dbhandler = shelve.open('DATABASE')

    Persistent Storage

    Flat database:

    like common text or binary file

    Persistent Storage in Relational Database

    Persistent Storage with object

    import pickle

    f = open('hello.txt', 'w')

    value = {1:'hello', 2:'NoAngels'}

    pickle.dump(value, f)

    #####Read the object#####

    f = open('hello.txt', 'r')

    pickle.load(f)

    July 24

    Something About Python Class

    Class person:

        name = 'NoAngels'

        def __init__(self):

            self.name = person.name

    First name is class attribute,and second is instance attribute.With class attribute ,we can access like classname.classattributename,while access to instance attribute ,we would use this:self.instanceattribute

    isinstance() and issubclass() always exists for they are in __builin__ module

    isinstance(instancename,classname)

    issubclass(classA,classB)

    Maybe some magic for overload:

    class test:

        def __init__(self,x,y):

            self.x = x

            self.y = y

        def __add__(self,other):

            return (self.x + other.x,self.y + other.y)

    #test file

    obj = test(10,20)

    obj2 = test(20,30)

    print obj + obj2

    #this will print (30,50)

    Python Exception

    try/except try/finally

    try:

        pass

    except [IndexError,IOError,ZeroDivisionError] :

        pass

    [else:

        pass]

    The part of else only execute when no exceptions raise!

    ImportError

    July 23

    dict中获取不存在得键

    You can write like this:

    try:

    print a['noSuchKey']

    except KeyError:

    print 'no such key'

    or just write like this

    print a.get('noSuchKey',None)

    使tuple可变???

     

    OS如何改变tuple,有点不可思议,其实说到底还是没有改变tuple,只是用了一种替代得方法而已.

    a = (1,2,3,4)

    现在要添加一个元素,在2和3之间,

    a = a[0],a[1],2.5,a[2],a[3]

    So easy.haha!

    July 19

    刚写的烧歌器,非IDE

    可能还有bug,呵呵,输入绝对路径.c:/music/noangels.mp3
    *********仅供参考************
    以下源码:
    #--*--coding:gbk --*--
    print '烧歌器V1.0.0 Writing by NoAngels' 
    files = []
    while 1:
        temp = raw_input("输入你即将要合并的完整的文件名,为避免错误,请只输入mp3格式的文件,输入q退出:")
        if temp[:-1] == 'q':
            break
        files.append(temp[:-1])
    if len(files) == 0:
        print '你没有输入欲合并的文件'
        exit()   
    import time,os,re
    outfileName = raw_input('请输入合并后的文件名,自动添加后缀mp3:')
    outfile = open(outfileName[:-1] + '.mp3', 'wb')   
    print outfileName[:-1] + '.mp3',
    begin = time.clock()
    for file in files:
        try:
            print '从' + file + '中读取数据,请稍后...'
            fp = open(file, 'rb')
            print '开始写入数据'
            outfile.write(fp.read())
            print file + '写入完毕'
            fp.close()
        except IOError:
            print '发生错误,请检查文件是否存在'
            outfile.close()
            os.remove(re.sub(r'\\',r'/',os.getcwd() + '\\' + outfileName[:-1] + '.mp3'))
            exit()
    outfile.close()
    end = time.clock()
    print '花费时间: %f 秒' % (end - begin)

    Python中的合并文件的簡單實現

    infiles = ['test.py','test2.py','test3.py','test4.py','test5.py']

    outfile = open('out', 'w')

    for infile in infiles:

        fp = open(infile, 'r')

        outfile.write(fp.read())

        fp.close

    outfile.close

    #成功合并文件

    Python中的*args,**kwargs

    兩個都是可變參數.

    *args返回一個無名參數的tuple

    **kwargs返回帶關鍵字的dict

    如:

    def foo(*args,**kwargs):

        print *args

        print **kwargs

    foo(1,2,3,4,name='NoAngels',job='manager')

    這個將產生一下輸出

    (1,2,3,4)

    {'name':'NoAngels','job':'manager'}

    個人認為用來創建字典是不錯的選擇.呵呵

    def foo(**kwargs):

    return kwargs

     

    foo(name='NoAngels',job='manager')

     

    --->{'name':'NoAngels','job':'manager'}

    Python中的歐幾里德算法

    def gcd(x,y):

        r = x % y

        if r > 0 :

            x, y, r = y, r, y % r

        return y

    #下面是遞歸方式算法

    def gcd2(x,y):

        r = x % y

        if r != 0 :

            gcd2(y,r)

        else:

            return y

    Python中的编码处理

    Python中字符串编码分为处理编码和传输编码.

    处理编码是一种内部编码即unicode,需要先将字符串转为内部处理编码,然后再转换为传输编码.

    如:

    a="中国"

    a.decode('gbk').encode('utf-8')

    or

    unicode(a,'gbk').encode('utf-8')

    July 15

    Python重点知识记录一

    1.Python是动态类型语言,又是强类型语言,动态获取类型,获取类型之后默认不能被转换
    2.doc string 默认都用"""定义,最后每次都定义doc string
    3.Python不支持行内比较,不存在要比较却意外赋值的情况
    4.Dictory没有顺序概念,删除元素del
    5.List删除元素用remove,注意pop用法,另外用in检测是否在List内容 'c' in list
    6.列表过滤语法[elem for elem in li if len(elem) > 1]注意两个方括号
    7.and a or b模拟三位操作符 ? : 当a为布尔假的时候会出现意外结果