zoukankan      html  css  js  c++  java
  • Python 小试牛刀

    练一练

    统计系统内存

    统计系统内存
    free 命令等同于查看系统文件 cat /proc/meminfo

    需要两个重要的方法
    line.startswith('字符串') #找开头符合这个字符串的进行判断,返回布尔值

    help(line.startswith())
    查看帮助

    startswith(...)
        S.startswith(prefix[, start[, end]]) -> bool
        
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
    

    举例:

    In : a = 'zxc'
    
    In : a.startswith("z")
    Out: True
    
    In : a.startswith("x")
    Out: False
    
    In : a.startswith("a")
    Out: False
    

    line.split() #默认以空格开始分割,还可以指定符号分割,类似于awk -F '' "
    help(line.split())
    查看帮助

    split(...)
        S.split([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are removed
        from the result.
    

    举例:

    In : a = "a jfbjk. [asd[14"
    
    In : a.split('[')[0]
    Out: 'a jfbjk. '
    
    In : a.split('[')[1]
    Out: 'asd'
    
    In : a.split('[')[2]
    Out: '14'
    

    字符串格式化输出
    " %.2f " 字符格式化输出 ,可以用于浮点数的输出,保留两位小数

    举例:

    In : a = 132.11111111
    
    In : "%.2f" % a
    Out: '132.11'
    
    In : "%.1f" % a
    Out: '132.1'
    
    In : type(a)              #原本为浮点数
    Out: float
    
    In : type(("%.1f" % a))   #格式化输出后变为字符串
    Out: str
    

    "%.2s" 字符格式化输出 ,和"%.2f"类似

    In : a = 123.123123
    
    In : "%.1s" % a
    Out: '1'
    
    In : "%.2s" % a
    Out: '12'
    
    In : "%.3s" % a
    Out[: '123'
    
    In : "%.4s" % a
    Out: '123.'
    
    In : "%.5s" % a
    Out: '123.1'
    
    In : "%.6s" % a
    Out: '123.12'
    

    统计内存大小:

    #!/usr/bin/python
    with open("/proc/meminfo") as fd:         # with open() as object
        for line in fd:                       #for 循环去遍历对象
            if line.startswith("MemTotal"):    #查找行开头匹配的内容,返回布尔值
                total = line.split()[1]         #返回一个列表,存储在一个变量,是字符串然后切割。类似'awk -F'的切割,取其第二个元素 
                continue                        #继续执行,跳过下面的if,直接跳到下一次循环
            if line.startswith("MemFree"):     #查找行开头匹配的内容,返回布尔值
                free = line.split()[1]          #返回一个列表,存储了一个变量,即为一个对象,然后切割取其值
                break                           #跳出循环
    print total,free                          #输出值
    print "%.2f" % (int(total)/1024.0) + " M"   # '%.2f'格式化输出字符串,适用于小数的取值,类似'%s'
    print "%.2f" % (int(free)/1024.0) + " M"
    

    输出结果:

    [root@hc python]# python cat_free.py 
    1883452 1606848
    1839.31 M
    1569.19 M


    输入三个整数x,y,z,请把这三个数由小到大输出。
    程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换, 然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。

    #!/usr/bin/python
    x = input("input number for x : ")
    y = input("input number for y : ")
    z = input("input number for z : ")
    a = 0
    if x > y:
    #   x <--> y
        a = x
        x = y
        y = a
        if x > z:
    #     x <--> z
            a = x
            x = z
            z = a
    if  y > z:
    #   y <--> z
        a = y
        y = z
        z = a
        if x > y :
            a = x
            x = y
            y = a
    print str("x : ")+ str(x)
    print str("y : ")+ str(y)
    print str("z : ")+ str(z)
    

    输出结果:

    [root@hc python]# python input_xyz.py 
    input number for x : 1
    input number for y : 2
    input number for z : 3
    x : 1
    y : 2
    z : 3
    input number for x : 1
    input number for y : 3
    input number for z : 2
    x : 1
    y : 2
    z : 3
    input number for x : 2
    input number for y : 1
    input number for z : 3
    x : 1
    y : 2
    z : 3
    input number for x : 2
    input number for y : 3
    input number for z : 1
    x : 1
    y : 2
    z : 3
    input number for x : 3
    input number for y : 1
    input number for z : 2
    x : 1
    y : 2
    z : 3
    input number for x : 3
    input number for y : 2
    input number for z : 1
    x : 1
    y : 2
    z : 3

    企业发放的奖金根据利润提成。

    利润(I)低于或等于10万元时,奖金可提10%;
    利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;
    20万到40万之间时,高于20万元的部分,可提成5%;
    40万到60万之间时,高于40万元的部分,可提成3%;
    60万到100万之间时,高于60万元的部分,可提成1.5%,高于 100万元时,超过100万元的部分按1%提成,
    从键盘输入当月利润I,求应发放奖金总数?

    答:

    #!/usr/bin/python
    i = raw_input("input the money: ")
    i = float(i)/10000
    
    # i <= 10
    if i <= 10:
        z = (i*0.1)*10000
        print (str("i<10   :") + str(z)) + " RMB"
    
    # 10 - 20 
    elif i >= 10 and i < 20:
        a = (i*0.1)*10000
        b = ((i-10)*0.1)*10000
        print str("i<10    :") + str(a) + " RMB"
        print str("20>i<10 :") + str(b) + " RMB"
        print "total  :" ,a+b,
        print "RMB"
    
    #20 - 40
    elif i >= 20 and i < 40:
        c = ((i-20)*0.05)*10000
        print str("40>i<20  :") + str(c) + " RMB"
    
    #40 - 60
    elif i >= 40 and i < 60:
        d = ((i-40)*0.03)*10000
        print str("60>i<40  :") + str(d) + " RMB"
    
    #60 - 100 . >100
    elif i >= 60 and i < 100:
        e = ((i-60)*0.015)*10000
        print str("100>i<60  :") + str(e) + " RMB"
    elif i >= 100:
        f = ((i-100)*0.01)*10000
        print str("i>100    :") + str(f) + " RMB"
    

    输出结果

    [root@hc python]# python total_i.py 
    input the money: 100000
    i<10   :10000.0 RMB
    
    [root@hc python]# python total_i.py 
    input the money: 123456768
    i>100    :1224567.68 RMB
    
    [root@hc python]# python total_i.py 
    input the money: 1200000
    i>100    :2000.0 RMB
    
    [root@hc python]# python total_i.py 
    input the money: 23
    i<10   :2.3 RMB
    
    [root@hc python]# python total_i.py 
    input the money: 230000
    40>i<20  :1500.0 RMB
    
    [root@hc python]# python total_i.py 
    input the money: 390000
    40>i<20  :9500.0 RMB


    练习1

    1. 有1、2、3、4个数字,能组成多少个互不相同且无重复数字的 三位数? 都是多少?
      1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。
    #!/usr/bin/python
    # -*- coding:--utf8 -*-
    a = []   
    for i in range(1,5):
        for x in range(1,5):
            for z in range(1,5):
                if (i != x and x != z and i !=z ):
                    b = (i*100+x*10+z)
                    a.append(str(b))
    print a
    print len(a)    
    
    1. 打印出所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个“水仙花数”,因为

    153=1的三次方+5的三次方+3的三次方。
    程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

    #!/usr/bin/python
    # -*- coding:--utf8 -*-
    x = []
    for i in range(100,1000):
        a = str(i)[0]
        b = str(i)[1]
        c = str(i)[2]
        d = a+b+c
        if str(a**3+b**3+c**3) == d:
            x.append(d)
    print d   
    
    1. 两个乒乓球队进行比赛,各出三人。
      甲队为a,b,c三人, 乙队为x,y,z三人。
      已抽签决定比赛名单。有人向队员打听比赛的名单。
      a说他不和x比, a != x
      c说他不和x,z比, c != x and c != z
      请编程序找出三队赛手的名单。

    先理解排序的整列
    a b c
    x y z
    0 1 2

    #!/usr/bin/python
    # -*- coding:--utf8 -*-
    import itertools
    for i in itertools.permutations('xyz'):
        if (i[0] != 'x') and (i[-1] != 'z') and (i[-1] != 'x'):
            print "a vs %s, b vs %s, c vs %s" % (i[0], i[1], i[2])
    

    import itertools
    itertools.permutations()
    解释:
    可以直接将'xyz'生成包含所有排列的列表。
    另外两个相关的库方法分别是:

    1. itertools.product()生成笛卡尔数列(即包括所有排列方式,
    2. itertools.combinations()生成所有组合的列表。就生成项的数目而言,product() > permutations() > combinations()。
      本题中,permutations('xyz', 3)可生成6组排列方式,而如果换成combinations('xyz', 3),则只有1种组合方式('x', 'y', 'z')。

    练习2

    1. 将一个正整数分解质因数。例如:输入90,打印出90=233*5。
      程序分析:对n进行分解质因数,应先找到一个最小的质数i,然后按下述步骤完成:
      (1)如果分解后商为1,则说明分解质因数的过程已经结束,打印出即可。
      (2)如果商不为1,则应打印出i的值,并用n除以i的商,作为新的正整数进行分解,重复执行第一步。
      (3)如果n不能被i整除,则i的值加1,重复执行第一步。
    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    
    num = int(raw_input("请输入要分解的正整数:"))
    
    temp = []
    while num!=1:
        for i in range(2,num+1):
            if num%i == 0:
                temp.append(i)
                num = num / i
                break
    print temp
    
    1. 猴子吃桃问题:
      猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个,
      第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
      以后每天早上都吃了前一天剩下的一半零一个。
      到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
      程序分析:采取逆向思维的方法,从后往前推断。
    #!/usr/bin/python
    # -*- coding:--utf8 -*-
    a = 1
    b = 1
    print "第10 天剩下桃子: %s " % a
    for i in range(9,0,-1):
        a = ((a + 1 ) *2)
        print "第 %s 天剩下桃子: %s " % (i,a)
    for i in range(1,11):
        b = ((a+1)*2)
    print  "total : %s" % b
    

    输出:

    [root@hc python]# python monkey_eats_the_peach.py 
    第10 天剩下桃子: 1 
    第 9 天剩下桃子: 4 
    第 8 天剩下桃子: 10 
    第 7 天剩下桃子: 22 
    第 6 天剩下桃子: 46 
    第 5 天剩下桃子: 94 
    第 4 天剩下桃子: 190 
    第 3 天剩下桃子: 382 
    第 2 天剩下桃子: 766 
    第 1 天剩下桃子: 1534 
    total : 3070
    
    

    类型转换 统计系统剩余的内存

    类型转换

    help(int)

    class int(object)
     |  int(x=0) -> int or long
     |  int(x, base=10) -> int or long
     |  
     |  Convert a number or string to an integer, or return 0 if no arguments
     |  are given.  If x is floating point, the conversion truncates towards zero.
     |  If x is outside the integer range, the function returns a long instead.
     |  
     |  If x is not a number or if base is given, then x must be a string or
     |  Unicode object representing an integer literal in the given base.  The
     |  literal can be preceded by '+' or '-' and be surrounded by whitespace.
     |  The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
     |  interpret the base from the string as an integer literal.
    

    十六进制字符串转为十进制
    int('12',16) #16 为十六进制!
    18

    int('0x12',16) #0x12的十进制为 18
    18

    十进制转为十六进制
    hex(10) #括号里面的转为十进制
    '0xa' #10转16进制

    In : type(hex(1)) #返回一个字符串
    Out: str

    十进制转为字符串
    str(10)
    '10'

    字符串转为十进制
    int('10') #必须是纯数字的,不然会报错

    MAC 地址转换

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    macaddr = 'C8:60:00:8E:6F:aa'     #MAC地址
    mac = macaddr[:-2]             #切片
    a = macaddr[-2:]               #取值
    b = int(a,16)+1                #16转10进制
    if b in range(10):            #判断b是不是在0-9中
        c = hex(b)[2:]            #是,则10转16进制,切片
        c = '0' +c                # 因为是单数 所以加个0,都是字符串
    else:
        c = hex(b)[2:]            #不在0-9内
        if len(c) == 1:           #判断长度是不是1位数
            c = '0' + c           #是一位数则加0,不齐
    #c = hex(b)[-2:]           #可以换这种写法,转10进制
    # c = hex(b).split('x')[-2]  -> '94'     #以‘x’分割符,分割
    new = mac+c                   #字符串相连
    print macaddr
    print new.upper()             #全部大写,补齐
    

    类型转换

    1.字符串转列表
    list(string)

    s = 'abv'
    list(s)
    ['a','b','v']
    

    2.列表转字符串
    ''.join(list)

     s
    'abcv'
    
    list(s)
    ['a', 'b', 'c', 'v']
    
    ''.join(s )
    'abcv'
    

    3.字符串转元组
    tuple(srting)

     s = 'asda'
    
     tuple(s)
     ('a', 's', 'd', 'a')
    

    4.元组转字符串
    ''.join(tuple)

     tuple(s)
     ('a', 's', 'd', 'a')
    
     ''.join(s)
     'asda'
    

    补充

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    

    python 2 解释出来是用的ASCII 码,需要加上面那段
    python 3 默认 utf-8



  • 相关阅读:
    Postgresql 常用操作
    捡回reset的未提交修改
    Excel 97-2003版本内部结构与查看方法
    【WPF】EntityframeworkCore Update注意事项
    Mac版StarUML破解方法
    Excel2016 自定义RTDServer添加方法
    apache中开启SSL设置方法
    软件开发中的常用工具
    编程风格统一配置EditorConfig
    Windows10简单启动项目添加方法
  • 原文地址:https://www.cnblogs.com/huidou/p/10758094.html
Copyright © 2011-2022 走看看