码迷,mamicode.com
首页 > 其他好文 > 详细

2015-11-15 第四天

时间:2015-11-21 00:25:37      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

冒泡算法

要求:给定一个列表 [13,22,6,99,11] 通过程序实现让他们可以从小到大排序。

思路:让相邻的两个数互比大小,存在大数就放在右边。

我的实现:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = lilon
li = [33,11,88,77,44,345,223,113,555,23,3]
print li
print "**************************8"

#定义冒泡函数,计算排序,最大数放在右面
def maopao():
    #循环,从1开始,例如range(1,5) 1,2,3,4 注意没有5
    for n in range (1,len(li)):
        #循环,从0开始到 例如range(5-1 4) range(5-2 3) range(5-3 2) range(5-4 1)
        for m in range(len(li)-n):
            #给num1赋值 li[m]
            num1 = li[m]
            #给num2赋值 li[m+1]
            num2 = li[m+1]
            #比较num1 num2
            if num1 > num2:
                #通过临时变量temp交换li[m] 和 li[m+1]
                temp = num1
                li[m] = num2
                li[m+1] = temp

        print li
    print li
    pass


#定义一个主函数
def main():
    maopao()

#限制程序入口
if __name__ =="__main__":
    main()

详说修改配置文件的方法

默认配置

global       
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend www.oldboy.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000

原配置文件

修改需求

1、查
    输入:www.oldboy.org
    获取当前backend下的所有记录

2、新建
    输入:
        arg = {
            bakend: www.oldboy.org,
            record:{
                server: 100.1.7.9,
                weight: 20,
                maxconn: 30
            }
        }

3、删除
    输入:
        arg = {
            bakend: www.oldboy.org,
            record:{
                server: 100.1.7.9,
                weight: 20,
                maxconn: 30
            }
        }

需求
我的实现
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = lilon
import os
import json

#定义好一个函数,用来做查找
def fetch(ha):
    backendlist = ha
    #先准备一个列表,在后面用来加入查到的backend字段下的server信息
    serverinfo = []
    # print "backend %s" %backendlist
    #使用with的方式打开文件,可以自动的关闭文件,减少我们出错误的可能
    with open ("oldboy.conf","r")as obj:
        """
        #灵活添加flag,使用flag做一个开关,匹配到了相关的backend就把flag设置为True,
        直到遇到了backend开头的其他的字段,就把flag设置为False,
        中间的就是我们需要的信息,使用列表的append()方法就可以添加了
        """
        flag = False
        #循环,一次一行,处理大文件必须的方式
        for line in obj:
            if line.strip() == "backend %s" % backendlist:
                flag = True
                continue
            #灵活性代码 startswitch方法 匹配开头是backend的行
            if flag and line.strip().startswith("backend"):
                flag = False
                break
            """
            #当我们确认了flag是True,
            意味着上面已经找到了相关的backend,
            而且把flag设置为了True了,
            所以我们现在可以通过append()方法来把相关的server info
            加入到了列表里面
            """
            if flag and line.strip():
                serverinfo.append(line.strip())
    if serverinfo:
        return serverinfo




#定义一个函数,做增加
def backendadd(**dict_info):
    fetch_list = []
    backend_title = dict_info.get("backend")
    current_record_pre = "server {server} weight {weight} maxconn {maxconn}"
    current_record = current_record_pre.format(**dict_info.get("record"))
    fetch_list = fetch(backend_title)
    if fetch_list:
        if current_record in fetch_list:
            pass
        else:
            fetch_list.append(current_record)
            with open("oldboy.conf","r") as objConf, open("conf.temp","w") as objTemp:
                flag = False
                isWrite = True
                for line in objConf:
                    if line.strip() == "backend %s" %backend_title:
                        objTemp.write(line)
                        flag = True
                        continue
                    if flag == True and line.strip().startswith("backend"):
                        flag = False
                    if flag == True:
                        if isWrite:
                            for new_line in fetch_list:
                                temp = "%s%s\n" %(" "*8,new_line)
                                objTemp.write(temp)
                            isWrite = True
                    else:
                        objTemp.write(line)
            if os.path.isfile("oldboy.bak"):
                os.remove("oldboy.bak")
            os.rename("oldboy.conf","oldboy.bak")
            os.rename("conf.temp","oldboy.conf")
            return True
    else:
        with open("oldboy.conf","r") as objConf, open("conf.temp","w") as objTemp:
            for line in objConf:
                objTemp.write(line)
            objTemp.write("backend %s\n" %backend_title)
            objTemp.write("%s%s\n" %(" "*8,current_record))
        if os.path.isfile("oldboy.bak"):
                os.remove("oldboy.bak")
        os.rename("oldboy.conf","oldboy.bak")
        os.rename("conf.temp","oldboy.conf")
        return True

def delitem(**dict_info):
    fetch_list = []
    backend_title = dict_info.get("backend")
    current_record_pre = "server {server} weight {weight} maxconn {maxconn}"
    current_record = current_record_pre.format(**dict_info.get("record"))
    fetch_list = fetch(backend_title)
    if fetch_list:
        if current_record in fetch_list:
            with open("oldboy.conf","r") as objConf, open("conf.temp","w") as objTemp:
                if len(fetch_list) > 1:
                    for line in objConf:
                        if line.strip() == current_record:
                            continue
                        else:
                            objTemp.write(line)
                else:
                    for line in objConf:
                        if line.strip() == "backend %s" %backend_title:
                            continue
                        if line.strip() == current_record:
                            continue
                        else:
                            objTemp.write(line)
            if os.path.isfile("oldboy.bak"):
                os.remove("oldboy.bak")
            os.rename("oldboy.conf","oldboy.bak")
            os.rename("conf.temp","oldboy.conf")
            return True
        else:
            pass
    else:
        pass
    pass

def backup():
    os.remove("oldboy.conf")
    os.rename("oldboy.bak","oldboy.conf")



#定义一个主函数
def main():
    ha = "buy.oldboy.org"
    dictItem = {
            backend: buy.oldboy.org,
            record:{
                server: 101.1.71.90 100.1.7.90,
                weight: 22,
                maxconn: 3000
            }
        }
    userInput = int(raw_input("hi plese input your choice:\n 1.search \n 2.add \n 3.del \n"))
    if userInput == 1:
        print "you select search."
        # userInputSearch = raw_input("input a backend url")
        searchEnd = fetch(ha)
        if searchEnd:
            for line in searchEnd:
                print line
            print "search End!"
        else:
            print "sorry not found!"

    elif userInput == 2:
        print "you select add."
        addEnd = backendadd(**dictItem)
        if addEnd:
            print "add successful"
        else:
            print "error!!!"

    elif userInput == 3:
        print "you select del."
        delEnd = delitem(**dictItem)
        if delEnd:
            print "del successful"
        else:
            print "no file in their"
            if os.path.isfile("oldboy.temp.conf"):
                os.remove("oldboy.temp.conf")

    elif userInput == 4:
        print "this is a super command"
        backup()
    else:
        print "sorry, i can not do that!!!"



#限制程序入口
if __name__ =="__main__":
    main()

 

lambda表达式

学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:

# 普通条件语句
if 1 == 1:
    name = wupeiqi
else:
    name = alex
  
# 三元运算
name = wupeiqi if 1 == 1 else alex
对于简单的函数,也存在一种简便的表示方式,即:lambda表达式
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = EchoRep

def func1(arg):
    return arg + 1
func2 = lambda a: a+1
func3 = lambda a,b: a+b




def lambdax():
    result = func1(100)
    print result
    result2 = func2(1000)
    print result2
    result3 = func3(100,211)
    print result3






#定义一个主函数
def main():
    lambdax()
    pass


#限制程序入口
if __name__ == "__main__":
    main()
lambda存在意义就是对简单函数的简洁表示

 

map

遍历序列,对序列中每个元素进行操作,最终获取新的序列

技术分享

li = [11, 22, 33]

new_list = map(lambda a: a + 100, li)
li = [11, 22, 33]
sl = [1, 2, 3]
new_list = map(lambda a, b: a + b, li, sl)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = EchoRep

def func1(args):
    return args ** 128

#定义一个主函数
def main():
    li =[2,3,4]
    l1 = [1,2,3]
    l2 = [2,3,4]
    l3 = [3,4,5]
    print map(lambda a,b,c:a+b+c,l1,l2,l3)
    pass


#限制程序入口
if __name__ == "__main__":
    main()

 

 

 

filter

对于序列中的元素进行筛选,最终获取符合条件的序列

 

 

技术分享

 

li = [11, 22, 33]

new_list = filter(lambda arg: arg > 22, li)

#filter第一个参数为空,将获取原来序列
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = EchoRep


li = [11,22,33,44]

#定义一个主函数
def main():
    print filter(lambda a:a>33,li)
    pass


#限制程序入口
if __name__ == "__main__":
    main()

 

reduce

用于累计操作,如累加,累乘等

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = EchoRep


li = [1,2,3,4,5,6,7,8,9]
#定义一个主函数
def main():
    print reduce(lambda arg1,arg2:arg1*arg2,li)


#限制程序入口
if __name__ == "__main__":
    main()

yield

暂时跳出了函数,但是下次可以继续使用,和continue要区分开

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = EchoRep

def func1():
    yield 1
    yield 2
    yield 3

def mrange(arg):
    seed = 0
    while True:
        seed = seed + 1
        if seed > arg:
            return
        else:
            yield seed



#定义一个主函数
def main():
    for i in mrange(10):
        print i


#限制程序入口
if __name__ == "__main__":
    main()

2015-11-15 第四天

标签:

原文地址:http://www.cnblogs.com/echorep/p/4982694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!