python实例(持续更新)

Posted 南山散人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实例(持续更新)相关的知识,希望对你有一定的参考价值。

1. 两个有序数列合并为1个有序数列

# -*- coding:utf-8 -*-
#两个有序数列合并为1个有序数列
str1 = [1,2,5,7,9]
str2 = [2,3,4,4.1,4.2,4.3,4.4]
def merge(str1,str2):
    merge_str = []
    len1 = len(str1)
    len2 = len(str2)
    i = 0
    j = 0
    while i < len1 and j < len2:
        if str1[i] <= str2[j]:
            merge_str.append(str1[i])
            i +=1
        else:
            merge_str.append(str2[j])
            j +=1
    if i < len1:
        for z in range(i+1,len1):
            merge_str.append(str1[z])
    if j < len2:
        for z in range(j+1,len2):
            merge_str.append(str2[z])
    return merge_str
print merge(str1,str2)

2.字典和列表读取速度测试

# coding:utf-8

#字典和列表的区别,列表是根据偏移量来读取的,字典是根据键的Hash来读取的

import time

testDict = {}

testList = []

for i in range(10000000):

    n = str(i)

    testDict[n] = i

    testList.append(n)

startTime = time.time()

if 1002231 in testDict:

    print yes

print time.time()-startTime

startTime = time.time()

if 1002231 in testList:

    print yes

print time.time()-startTime

 

3.冒泡排序

冒泡排序原理: 每一趟只能将一个数归位, 如果有n个数进行排序,只需将n-1个数归位, 也就是说要进行n-1趟操作(已经归位的数不用再比较)

 

# -*- coding:utf-8 -*-

def sort(num):

    for i in range(len(num)-1):       #负责设置冒泡排序进行的次数

        for j in range(len(num)-1-i):   #j为列表下标

            if num[j] > num[j+1]:

                num[j],num[j+1] = num[j+1],num[j]

    return num



num1 = [3,2,1,6,1]

print sort(num1)

 

4.倒叙输出原字符串

# -*- coding:utf-8 -*-

str1 = "python"

new_str = []

for i in range(len(str1)-1,-1,-1):

    new_str.append(str1[i])

print  .join(new_str)

#print new_str

 

5.统计字符串中出现最多的字符

# -*- coding:utf-8 -*-

def count(str1):
    Dic = {}
    maxnum = 0
    for i in str1:
        if i in Dic:
            Dic[i] = Dic[i]+1
        else:
            Dic.setdefault(i,1)
    for key,value in Dic.items():
        if Dic[key] > maxnum:
            maxnum = Dic[key]
            letter = key
    return letter,maxnum

str1 = "pythonpp"
print count(str1)

 

6.遍历指定路径下的所有文件

# -*- coding:utf-8 -*-
import os
# 枚举dirPath目录下的所有文件
# os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
# top -- 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)
# root 所指的是当前正在遍历的这个文件夹的本身的地址(所有的根地址)
# dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
# files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
def main(fileDir):
    for root, dirs, files in os.walk(fileDir):
        print "root:" + root
        for dir in dirs:
            print(os.path.join(root, dir))
        for file in files:
            print(os.path.join(root, file))

if __name__ == __main__:
    file = r"E:A"
    print main(file)

7.continue和break

#-*- coding:utf-8 -*-
i = 0
while i < 6:
    i +=1
    for j in range(4):
        #print j,
        # print "j","=",j
        if j == 2:
            break     #彻底跳出循环
        print "j","=",j
    for k in range(4):
        if k == 2:
            continue     #略下本次循环的剩余内容,直接进入下一次循环
        #print  k,
        print  "k","=",k
    if i > 3:
        break          #当I>3,跳出,后续的i不再输出
    #print i,
    print "i","=",i

 

8.求和运算(奇数和、偶数和)

#-*- coding:utf-8 -*-
sum = 0
for i in range(1,101):
    sum = sum + i
print sum

sum1 = 0
for i in range(1,101,2):
    sum1 = sum1 + i
print sum1

sum2 = 0
for i in range(0,101,2):
    sum2 = sum2 + i
print sum2

 

9. join()方法

 join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

s = ["apple","pear","orange"]
fruit = ".".join(s)
print fruit

 

返回结果:

apple.pear.orange

10.输入多行内容,并将输入结果写入到指定文件

#-*- coding:utf-8 -*-
#os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用‘
‘,Linux使用‘
‘而Mac使用‘
‘。
import os
def WriteFile(filename):
    fp = open(filename,"a")
    print "
请输入多行文字","(输入.号回车保存)"
    while True:
        content = raw_input("content:")
        if content == ".":
            break
        else:
            fp.write("%s%s" %(content,os.linesep))
    fp.close()

if __name__ == "__main__":
    WriteFile(r"F:AONE	est.txt")

 

11.读写文件

#-*- coding:utf-8 -*-
spath=r"F:AONE	est.txt"
f=open(spath,"w")
f.write("First line 1.
")
f.writelines("First line 2.
")
f.close()

f=open(spath,"r")
lines = f.readlines()
for line in lines:
    print line.strip()
# for line in f:
#     print("每一行的数据是:%s" %line)
f.close()

 

12.魔法方法

构造方法: __init__,对于子类的构造方法,需要调用父类的构造方法,有以下两种调用方式:

#-*- coding:utf-8 -*-
class bird:
    def __init__(self):
        self.hungry = False
    def eat(self):
        if self.hungry:
            print Aaaaa...
            self.hungry = False
        else:
            print No,thanks!

class songbird(bird):
    def __init__(self):  #如果重写了构造方法,需要调用父类的构造方法
        #(1)方法1:未绑定方法,通过类名调用,将self传递过去
        bird.__init__(self)
        #(2)#方法2:super函数,参数类和对象做参数,再调用父类init函数
        super(SongBird, self).__init__()
        self.sound = Squawk!

    def sing(self):
        print self.sound
if __name__ == "__main__":
    A = songbird()
    print A.sing()
    print A.eat()

 

13.简单的数据库应用程序(shelve)

#-*- coding:utf-8 -*-
import sys,shelve

‘‘‘

shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写:key必须为字符串,而值可以是

python所支持的数据类型

‘‘‘

def store_person(db):
    ‘‘‘
    Query user for data and store in the shelf object
    ‘‘‘
    pid = raw_input(Enter unique ID number: )
    person = {}
    person[name] = raw_input(Enter name: )
    person[age] = raw_input(Enter age: )
    person[phone] = raw_input(Enter phone number: )
    db[pid] = person
    
def lookup_person(db):
    pid = raw_input("Enter ID number: ")
    field = raw_input("what would you like to know?(name,age,phone)")
    field = field.strip().lower()
    print field.capitalize()+:,db[pid][field]

def print_help():
    print "The available command are: "
    print "store :Stores information about a person"
    print "lookup :look up a person from ID number"
    print "quit :Save change and exit"
    print "?    :Print this message"

def enter_command():
    cmd = raw_input("Enter command(? for help): ")
    cmd = cmd.strip().lower()
    return cmd

def main():
    database = shelve.open("D:\database.dat")
    try:
        while True:
            cmd = enter_command()
            if cmd == "store":
                store_person(database)
            elif cmd == "lookup":
                lookup_person(database)
            elif cmd == "?":
                print print_help()
            elif cmd =="quit":
                return
            
    finally:
        database.close()
    
if __name__ == "__main__":
    main()

 

14. 将字符串中大写字母转化为小写,小写转化为大写,标点和数字不做变化

#-*- coding:utf-8 -*-



str = "WWW.12kuqiao12.COM"



# print str.upper()   #全部转化为大写

# print str.lower()   #全部转化为小写

# print str.title()   #把每个单词的第一个字母转化为大写,其余小写



new_str = []

for i in range(len(str)):

    if str[i].islower():

        new_str.append(str[i].upper())

    elif str[i].isupper():

        new_str.append(str[i].lower())

    else:

        new_str.append(str[i])

print "".join(new_str)

# print str1.isdigit()  #判断是否是数字

# print str.isalnum()  #判断是否是字母和数字的组合

# print str2.isalpha()  #判断是否是字母

# print str3.isspace()  #判断是否为空格
 

15.求100以内的质数

#-*- coding:utf-8 -*-

num = []
for i in range(2,100):
    for j in range(2,i/2):
        if (i%j==0):
            break
    else:
        num.append(i)
print num
#-*- coding:utf-8 -*-
from math import sqrt

def main():
    for i in range(101,200):
        flag = 1
        k = int(sqrt(i))
        #print k
        for j in range(2,k+1):
            if i%j == 0:
                flag = 0
                break
        if flag == 1:
            print %d %(i),

if __name__ =="__main__":
    main() 

16. 1,2,3,4组成数字互不相同的3位数

#-*- coding:utf-8 -*-

count = 0

for i in range(1,5):

    for j in range(1,5):

        for k in range(1,5):

            if i != j and i != k and j != k:

                print i,j,k

                count +=1

print count

 

17.某个数,加100是一个完全平方数,再加上168又是一个完全平方数,求这个数;

#-*- coding:utf-8 -*-



import math

for i in range(0,1000):

    if i + 100 == int(math.sqrt(i+100))*int(math.sqrt(i+100)) and 
                            i + 268 == int(math.sqrt(i+268))*int(math.sqrt(i+268)):

        print i

 


18. 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

#-*- coding:utf-8 -*-
def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1

for i in fab(6):
    print i,

 

19.分解质因数

#-*- coding:utf-8 -*-

def main():
    n = int(raw_input("Enter a number:"))
    print n,=,
    while(n!=1):
        for i in range(2,n+1):
            if (n%i) == 0:           #余数9%2 1
                n /= i               #整除9/2 4
                if (n == 1):         #余1
                    print %d %(i)
                else:
                    print %d* %(i),
                break

if __name__ == "__main__":
    main()

 

     上述方法如果输入超过range的范围,则会报错,鉴于此新增了下列方法:

#-*- coding:utf-8 -*-
import math
number = int(raw_input("Enter a number: "))
list = []

def getChildren(num):
    isZhishu = True
    i = 2
    square = int(math.sqrt(num)) + 1
    while i <= square:
        if num % i == 0:
            list.append(i)
            isZhishu = False
            getChildren(num / i)
            i += 1
            break
        i += 1
    if isZhishu:
        list.append(num)

getChildren(number)
print list

 



以上是关于python实例(持续更新)的主要内容,如果未能解决你的问题,请参考以下文章

python实例(持续更新)

python 100例 (持续更新)

超详细的 Python 基础语句总结(多实例视频讲解持续更新)

可以更新片段而不是创建新实例吗?

Jenkins 持续化部署实例

Python小知识点(持续更新)