# #class resultPdt(object):
# #def getResult(id,opr):
# print ('a =',5)
# x,y,z = 1,2,3
# print(x,y,z)
# x,y,z = y,z,x
# print(x,y,z)
# #a,b,rest* = [1,2,3,4] //python3
#
# x = c()
# y = c()
#
# x = y
# y = c()
#
# a = 'b'
# a *= 2
# print(a)
# num = input('number?\n')
# if (num == 1):
# print ("==")
# else: print("!=")
# x=1
# y=1
# if x <= y <= z:
# print(1)
# if(x is not y): #理论上根据判断对象原则;即使x和y值相等,也不该是同一个对象啊;
# print (2)
#
# x = [1,2,3]
# y = [2,4]
# print(x is not y)
# del x[2]
# y[0] = 1
# y.reverse()
# for i in x:
# print (i)
# print(x is y)
# x = [1]
# y = [1] #地址不同
# print(x is not y) #true
# #实践证明,为列表时,是不同对象
# x = 1
# y = 1
# print(x is not y) #false 为值时为相同对象
#
# x = 2
# y = 1
# print ('第二次',x is not y) #true
# x = 1
# print (x is not y) #false 地址相同,文档提示使用is比较值和字符串不可取
# #因为python内部操作该字符串的方式不可控导致结果不可预测;那么内部操作方式又是什么?
#
# print("abc"<"aba") #按位进行字母排列顺序比较
# print(ord("a"),ord("A"),chr(54),"adFdCSEf".upper(),"adFdCSEf".upper().lower())
#
# print ([2,{1,3},4]<[2,{1,3},5]) #花括号究竟是啥玩意啊;集合set
# print ([2,[1,3],4]<[2,[1,3],5])
#
# name = input('input name')or "random" #随机名称生成;
# print (name)
#
# b = 3
# print (5 if b == 5 else 1) #b在未定义时为不可预测态,时无法比较;
#
# # 断言机制:先验
# age = -1
# assert 1<age<19 #用于检查函数和变量;不满足条件直接从这里中断掉
#
# name = ''
# while not name or name.isspace():
# name = input ("inputname?:") #or "unknown"
# print ("欢迎%s!"%name) #%s打印消除空格 #注意:依赖于缩进识别语句快;
# print ("欢迎!",name)
#
# s = 0
# for a in range(10):
# s += a
# print ("%d"%s) #循环语句块外
#
# s = 0
# for a in range(10): #range(10) =[0,1,2,3,4,5,6,7,8,9] 集合
# s += a
# print ("%d"%s) #循环语句块内,直至找到缩进为止; #xrange用法
#
# d = {'a':1,'b':2,"c":3} #字典 python单引号和双引号是否有区别?
# for key in d:
# print (key,':',d[key])
# print (key)
# print (d[key])
# print('a','b','c','d',123)
#
# 并行迭代
# name = ['a','b','c','d']
# for i in name:
# print(i)
# sex = [0,0,1,1,0,1]
#
# for i in range(len(name)):
# print (name[i],': %d'%sex[i]) #分片
# # 下方需要继续探讨修改为 for a in zip(name,sex)时,输出存疑结果的原因
# print("内建函数:")
# zip(name,sex) #压缩多个序列为一个
# for a,b in zip(name,sex):
# print(a,b)
# #
# for a,b in zip(range(5),range(5)): #python 3.0中,xrange究竟被替换成了什么
# print(a,b)
# #编号迭代
# name = ['a','b','c','d']
# for i in range(len(name)): #创建游标或者索引i
# if name[i] == 'c':
# name[i] = "e"
# for i in name: #此处i为集合或列表中的元素
# print(i)
#
# name = ['a','b','c','d']
# for i in name:
# if 'c' in i:
# idx = name.index(i) #取得含有对应元素的索引
# name[idx] = 'e'
# for i in name:
# print(i)
#
# name = ['a','b','c','d']
# idx = 0
# for i in name:
# if "c" in i:
# name[idx] = 'e'
# idx += 1 #
# for i in name:
# print(i)
# 内建函数迭代
# name = ['a','b','c','d']
# for index,n in enumerate(name): #enumerate列举出键值对;
# if 'c' in n:
# name[index] ='e'
# for i in name:
# print (i)
#
#
# name = ['e','a','b','c','d']
# s = "+" #
# name = sorted(name) #返回列表
# name = list(reversed(name)) #返回对象地址
# name = s.join(reversed(name)) #遍历列表,将s加入序列
# print(name)
#
# for while 循环中的break,continue,else语句
# from math import sqrt
# for n in range(99,81,-1):
# x = sqrt(n) #开方后结果默认为浮点数;
# if x == int(x):
# print (int(x))
# break
# else: print('not find')
# while True:
# temp = input('input value:')
# if temp.isspace():
# continue
# if not temp:
# break
# print
#
# list = [x*x for x in range(5) if x%3 == 0]
# print(list)
#
# list = [(a,b)for a in range(10)for b in range(10)]
# print(list)
#
# a = tuple()
# b = (0,1,2)
# print(a,b)
# result = []
# for x in range(3):
# for y in range(3):
# result.append((x,y))
# print(result)
#
# #字典序
# girls = ['ali','ber','cla']
# boys = ['chr','arn','bob']
# letterGirls = {}
# for i in girls:
# letterGirls.setdefault(i[0],[]).append(i)
# print([(b,g) for b in boys for g in letterGirls[b[0]]])
# #以男孩名首字母为索引,在创建的字典中中查找对应值
#
# pass
# def a():
# x = 1
# del x
# ##print(x) #移除对象名以及对象引用
#
# exec
# from math import sqrt #本段运行不成功,并且对于 scope['sqrt']存疑,因为
# # 并不是将语句字符串写入命名空间,而是仅仅将sqrt;但代码在sqrt报错
# scope = {}
# exec ("sqrt = 1") in scope
# sqrt(4)
# scope['sqrt']
# scope.keys()
#
# eval
# eval用于求值
# eval(input("evalue:")) #未能计算出结果
#
# scope = {}
# scope['x'] = 2
# scope['y'] = 3
# eval('x*y',scope) #运行有问题,不明觉厉
#
# scope = {}
# exec ('x=2' in scope)
# eval('x*x',scope) #运行有问题,不明觉厉
#
# fibs = [0,1]
# for i in range(8):
# fibs.append(fibs[-2] + fibs[-1])
# print(fibs)
#
# def fibs(num):
# '计算菲薄纳妾数列' #该函数说明语句不同于注释,它是作为函数的一部分与之一起存储的;
# fibs = [0,1]
# for i in range(num-2):
# fibs.append(fibs[-2] +fibs[-1])
# print(fibs) #没有给返回值时,会返回none
# return fibs #递归程序的运行时间较长,和C相比可见python的速度;
#
# fibs(64)
# print(fibs.__doc__) #返回函数说明语句
# help(fibs) #打印函数相关信息
#
# def change(n):
# n[0] = 1
# return print(n)
# p = [0,1]
# change(p)
# print (p)
#
# 以下两块展示了列表复制与多个指向的区别
# n = [0,1]
# x = n
# print(n is x)
# print(n == x)
#
# x = n[:] #以切片形式得到列表副本
# print(n is x)
# print(n == x)
# 字典的嵌套,下面这段不是很明确;
#
# def init(data):
# data['first'] = {}
# data['middle'] = {}
# data['last'] = {}
# return print(data)
# temp = {}
# init(temp)
#
# def lookup(data,label,name):
# return data[label].get(name)
#
# def store(data,full_name):
# names = full_name.split()
# if len(names) == 2: names.insert(1,'')
# labels = ['first','middle','last']
# for label,name inzip(labels,names):
# people =lookup(data,label,name)
# if people:
# people.append(full_name)
# else:
# data[label][name] = [full_name]
#
# 关键字参数和默认值
# def f1(name = 'unknown',greet = 'hi'):
# print('%s,%s!'%(name,greet))
# f1('hello','12')
# #参数化赋值如下,可乱序
# f1(greet = '12',name = 'HELLO')
# f1()
# f1(name = 'lx')
# f1("s") #如果只给出一个实参,那么本编译器默认匹配第一个形参,但不建议这么做,可能有其他问题
#
# 收集参数:收集其余位置
# def print_param(*params):
# print (params)
# print_param(1,2,3)
# print_param("test")
#
# def print_param(title,*params):
# print (title,params)
# print_param('params:',1,2,3)
# print_param('params:') #不提供后续参数则为空元组
#
# 关键字
# def print_param(**params):
# print (params)
# print_param(x=1,y=2)
#
# def print_param(x,y,z=3,*pospar,**key):
# print(x,y,z)
# print(pospar)
# print(key)
# print_param(1,2,3,5,6,7,foo=1,bar=2)
#
# def store (data,*prm):
# data.append(prm)
# return print(data)
# a = []
# store(a,1,2,3,4)
#
# 反向;
# def add(a,b):
# s = a+b
# print(s)
# params = (1,2)
# add (*params)
#
# def star(**kwd):
# print(kwd['name'],'is',kwd['age'],'old')
# def opstar(kwd):
# print (kwd['name'],'is',kwd['age'],'old')
# args = {'name':'Mr.Gumby','age':42}
# star(**args)
# opstar(args)
# 拼接操作符传参也可以达到差不多效果;splicing? py3应该变了吧
#
# # 参数设置练习
# def story(**key):
# return 'a''\%(job)s called%(name)s.'%key
#
# def power(x,y,*others):
# if others:
# print('other param:',others)
# return print(pow(x,y))
# def interval(start,stop = None,step = 1):
# 'range() for step > 0'
# if stop is None:
# start,stop = 0,start
# result = []
# i = start
# while i<stop:
# result.append(i)
# i += step
# return print(result)
#
# print (story(job = 'lx',name = 'py'))
#
# params = {'job':'py','name':'lzk'}
# print (story(**params))
#
# del params['job']
# print (story(job = 'tec',**params))
#
# params = (5,)*2
# print('pay attention to the next')
# print(params)
# print(*params)
#
# power(*params)
#
# interval(10)
# interval(1,5)
# interval(3,12,4)
# interval(3,7)
#
# param = (3,4,5,6)
# param2 = [3,4,5,6]
# power(*param)
# power(*param2)
# 作用域
# def combine(param):
# print(param+globals()['param'])
# param = 'cell'
# combine('shr')
# # globals()用于获取全局变量的值
#
# 重定向全局变量:·
# x = 15
# def chgglobal():
# global y
# y = 25
# y += x
# print(x,y)
# chgglobal()
# print(x) #结果为2
# # global y
# print(y)
# 递归
# def fac(n):
# if n == 1:
# return 1
# else:
# return n*fac(n-1)
# print (fac(10))
#
# #顺序序列二分查找算法
# def search(seq,number,up,low):
# if up == low:
# assert number == seq[up]
# return up
# else:
# middle = (low+up)//2
# if number>seq[middle]:
# returnsearch(seq,number,up,middle+1)
# else:returnsearch(seq,number,middle,low)
# seq = [54,23,1,5,9,4]
# seq.sort()
# print(seq)
# print(search(seq,9,up = len(seq)-1,low = 0))
#
# map(str,range(10)) #搞不懂什么玩意
#
# def func(x):
# return x.isalnum()
#
# seq = ['foo','x4l','?!','**']
# filter(func,seq) #没输出,版本问题,不管了
# seq = ['foo','x4l','?!','**']
# [x for x in seq if x.isalnum()]
#
# seq = ['foo','x4l','?!','**']
# filter(lambda x:x.isalnum(),seq) #不知道如何输出
#
# num = [1,3,5,3,2,3,33,4]
# reduce(lambda x,y:x+y,num) #以上函数(另外还有apply函数)
# 3.0以上版本已经不再支持,转移到functools模块中
#
# def add(x,y):
# return x+y
# print(add(0,1))
# print(add('ui','designer'))
#
# class person(object): #(或括号内object)
# def setName(self,name):
# self.name = name
# def getName(self):
# return self.name
# def greet(self):
# print ('hello,','I am%s'%self.name)
#
# a = person()
# b = person()
#
# a.setName('lx')
# b.setName('lix')
#
# a.greet()
# b.greet()
# print(a.name)
# print(a.greet())
# 类和对象
# class person(): #(或括号内object)
# def setName(self,name):
# self.name = name
# def getName(self):
# return self.name
# def greet(self):
# print ('hello,','I am%s'%self.name)
#
# def greet2():
# print('no self')
#
# a = person()
# b = person()
# a.greet = greet2 #可以将类的某个属性绑定到某个普通函数上
# greet3 = b.greet #使用外部方法引用类的某个方法
#
# a.setName('lx')
# b.setName('lix')
#
# a.greet()
# # b.greet()
# # print(a.name)
# # print(a.greet())
# print(greet3())
#
# 私有属性和方法的声明
# class A:
# def __only(self):
# print ("can notsee!!")
# def _only(self):
# print ("can notsee") #单下划线的可以被外部访问,但不会被import *导入
# def only(self):
# print("publicmethod")
# def access(self):
# print('it is')
# self.__only()
# s = A()
# s.access()
# s._only()
# # s.__only() #类外屏蔽
# s._A__only() #根据解释器翻译机制形式,以类名连接方法进行访问
#2018年3月26日到此一游
# def a():
# pass
# {},[]
# def hello_1(greet = 'hello',name = '1'):
# print(greet,name)
#
# hello_1('hello','lx')
# hello_1(greet = 'hello',name = 'lx')
# hello_1(name = 'lx',greet = 'hello')
#
# name = [1,2,3,4]
# n = name[::]
# print(n)
#
# print(name[0:3])
# print(name[1:1])
# print(name[-3:-2]) #最后一个元素的索引是-1
# print(name[-2:]) #最后一个元素的索引是-1
#
# tup = (1,3,5,7)
# print(tup[:3])
#
# print('123456789'[::2]) #切片与range使用方式相同
#
# print(n)
# print(n is name)
# print(n == name)
#
# a = print(exec('print("hello")')) #执行语句
# b = print() #执行语句
# print(b) #执行语句
# print(eval('6+18*2')) #求值
# scope = {} #命名空间
# scope['x'] = 2;
# scope['y'] = 3;
# # print(eval('x*y',scope))
# print(scope)
#收集其余位置参数: 收集过程
# def x(*params):
# print(*params) #....将*号所有值放到一个元组中,然后使用
# print(params) #作为元组
# x('a','b')
# x('a')
# x()
# def x_2(**params):
# print(params)
# x_2(x=1,y=2,z=3)
# def x_3(x,y,z=3,*pos,**key):
# print(x,y,z)
# print(pos)
# print(key)
# x_3(1,2,3,4,5,'3',a=1,b=2)
#print(x*y)
#反转过程 元组
# def cal(x,y):
# return x+y
# pa = (1,2)
# print(*pa)
# print(cal(*pa))
#反转过程:字典
# def a3(greet='hello',name='lx'):
# print(greet,name)
# params = {'name':'ll','greet':'hh'}
# a3(**params)
# def gather(**kwds):
# return '%(job)s called %(name)s'%kwds
# print(gather(job = 'lx',name = 'wanniba'))
#
# def gather2(**kwds):
# return kwds
# print(gather2(job = 'lx',name = 'wanniba'))
# foo = lambda x: x*x
# print(foo(2))
# #
# class mem:
# #构造函数怎么写?
# members = 0
# def init(self):
# mem.members += 1
# m1 = mem()
# m1.init()
# m2 = mem()
# m2.init()
# print(mem.members)
#
# 超类
# class A:
# def init(self):
# self.blocked = [1]
# def filter(self,sequence):
# return [x for x in sequence ifx not in self.blocked]
# class B(A): #括号内表示超类,为继承的概念
# def init(self):
# self.blocked = [1]
# a = A()
# a.init()
# print(a.filter([1,2,3]))
#
# b = B()
# b.init()
# print(b.filter([1,23,41,23,121,11111,1,1,1,1,1,1,1]))
# print(issubclass(A,B)) #判断前一个类是后一个类的子类;
# print(issubclass(B,A))
# print(B.__bases__)
# print(A.__bases__)
# print(b.__class__) #判断对象所属的类
# print(isinstance(a,A))
# print(isinstance(b,A)) #子类对象亦然为父类实例,间接对象
# print(isinstance(a,B))
# 多重继承
# class clctor:
# def clc(self,exp):
# self.value = eval(exp)
# return self.value
#
# def talk(self):
# print('result is:','override')
#
# class talker:
# def talk(self):
# print('result is:',self.value)
# class talkclc(clctor,talker):
# def x(self):
# pass
#
# class talkclc2(talker,clctor):
# def x(self):
# pass
#
# tc = talkclc()
# print(tc.clc('1+2+3'))
# tc.talk() #被最早的同名方法覆盖
#
# tc2 = talkclc2()
# print(tc2.clc('1+2+3'))
# tc2.talk() #多重继承具有顺序性,以先继承的同名方法会覆盖之后继承的同名方法
#
# print(hasattr(tc,"talk")) #检查某类中某属性的存在
# print(hasattr(tc2,"talk")) #检查某类中某属性的存在
# #接口(协议,规范)
#
# 异常
# raise Exception('001')
# import exceptions
# dir(exceptions) #python3可能更换了异常模块的关键词/na
#
# 值或属性,对象,索引,键,变量,类型,文件,除数 个人总结为三类,文件,越界,类型
#
# class A(Exception):
# def sum(self):
#
# try:
# x = float(input("被除数"))
# y = float(input("除数"))
# print(x/y)
# except ZeroDivisionError:
# print("除数不能为0 ")
#
# a = A()
# a.sum()
#
# class A:
# flag = False
# def calc(self,exp):
# try:
# return eval(exp)
# except ZeroDivisionError:
# if self.flag:
# return ('非法除数0')
# else:
# raise
# a = A()
# print(a.calc('10/2'))
# # print(a.calc('10/0')) #默认不开启使其抛出异常,程序中断
#
# a.flag = True #开启异常处理机制,程序不用中断
# print(a.calc('10/0'))
# print("continue")
#
# def div():
# try:
# x = float(input("被除数"))
# y = float(input("除数"))
# z = x/y
# return z
# except ZeroDivisionError:
# return ("除数不能为0")
# except TypeError:
# return ("type notnumber") #事实上由于input默认输入为str,所以这个二者不可得兼;
# print (div())
#
# 捕捉多个异常时,用元祖括起来
# def div():
# try:
# x = float(input("被除数"))
# y = float(input("除数"))
# z = x/y
# return z
# except(ZeroDivisionError,TypeError,ValueError) as e: #py2版本为(a,b,c).e
# print (e)
# print(div())
#
# 捕捉所有异常
# def div():
# while 100:
# # noinspectionPyUnreachableCode
# try:
# x = float(input("被除数"))
# y = float(input("除数"))
# z = x/y
# return z
# # except:
# # print('自定义异常,somethingwrong') 这种方法掩盖了异常的原因,不推荐使用
# except Exception as e: #py2版本为(a,b,c).e
# print (e) #有异常则继续
# else:
# break #无异常则中断
# finally:
# print("cleancard") #finally子句一定会执行,不因跳出循环而不执行,也就是说
#
# #无论它之前是什么语句,(描述可能不准确,但为了突出)一定会执行;
# print(div())
#
# def des(person):
# print('des of people')
# print('age',person['age'])
# if 'occu' in person:
# print('occu:',person['occu']) #通过key访问value
#
# pers = {'age':15,'occu':'tec'}
# des(pers)
# #
# class F:
# def __init__(self):
# self.age = 42
#
# class G:
# def __init__(self,value = 42):
# self.age = value
#
# f = F()
# g = G(45) #__del__析构方法,对象回收前调用,具体时间暂不可控
# print(f.age)
# print(g.age)
# class A:
# value = True
# # def __init__(self):
# # self.value = True
# def eat(self,value):
# self.value = value
# if self.value:
# print('Ah...')
# else:
# print('No')
#
# def hello(self):
# print('hello')
# class B(A):
# pass
#
# def __init__(self):
# # super().__init__() #使用super函数,二者任选其一,
# # super函数的优势在于多继承时,一个super就可以全部引入初始化,
# # X.__init__(self)而下面这种方法可以按需要裁剪;
# # A.__init__(self) #在子类中调用父类的构造方法 or
#
# self.value2 = False
#
# def hello(self,value):
# print('no hello',value)
#
# b = B()
# b.hello(12) #如果此时子类要调用已经被覆盖的父类方法;super.f()是不可行的;
# b.eat(False)
#
# 序列和映射规则:项目
#
# def check(key):
# if not isinstance(key,int): #python3只有int型
# raise TypeError
# if key < 0:
# raise IndexError
#
# class seq:
# def __init__(self,start = 0,step =1):
# self.start = start
# self.step = step
# self.changed = {}
# def __getitem__(self, key):
# check(key)
# try:
# return self.changed[key]
# except KeyError:
# returnself.start+key*self.step
# def __setitem__(self, key, value):
# check(key)
# self.changed[key] = value
#
# s = seq(step = 5,start = 0)
# print(s[3])
# s = seq(0,2)
# print(s[3])
# 回顾序列分片和遍历
#
# class count(list):
# def __init__(self,*args):
# super(count,self).__init__(*args)
# #注意*args(无键值类似list)
# # 和**kwargs(类似dictionary),
# self.c = 0
# def __getitem__(self, index): #访问次数还可以使用pop函数来统计
# self.c += 1
# return super(count,self).__getitem__(index)
#
# c1 = count(range(10))
# print(c1)
# c1.reverse() #反转元素
# print(c1)
# del c1[3:6]
# print (c1)
# print(c1.c)
# print(c1[0]+c1[3])
# print(c1.c)
# class rec:
# def __init__(self):
# self.width = 0
# self.height = 0
# def setSize(self,size):
# self.width,self.height = size
# def getSize(self):
# return self.width,self.height
#
# r = rec()
# r.width = 10
# r.height = 5
# print(r.getSize()) #注意size为元组
# print(r.setSize((150,100)))
# print(r.height)
#
# property函数
# class rec:
# def __init__(self):
# self.width = 0
# self.height = 0
#
# def getSize(self):
# return self.width,self.height
#
# def setSize(self,size):
# self.width,self.height = size
#
# size = property(getSize,setSize)
# r = rec()
# r.width = 10
# r.height = 5
# print(r.size)
# r.size = 150,100
# print(r.width) #property将添加的自定义属性”改造“成普通属性(fget,fset,fdel,doc--))
# #####################################随机实验####################################
# for x in range(1,37,1): #
# for y in range(1,37,1): #
# for z in range(1,37,1): #
# if(z == 36/(x*y)): #
# if(x<=y<=z): #
# print(x,y,z,'',x+y+z) #至于大儿子眼睛是蓝色的,表示很有疑惑; #
################################################################################
#
# 静态方法和类成员方法
#
# class M:
# @staticmethod #注解为静态方法;没有self参数
# def smeth():
# print('static method')
#
# @classmethod
# def cmeth(cls):
# print('类成员方法')
#
# M().smeth() #对于静态方法,可以创建对象进行访问,但不推荐这种做法,一来体现不出静态方法的价值,二来浪费内存。
# M.smeth()
# M().cmeth()
# m = M()
# m.smeth()
# m.cmeth()
#
# __getattr__、__setattr__等
# class r:
# def __init__(self):
# self.width = 0
# self.height = 0
# def __setattr__(self, name, value):
# if name == 'size':
# self.width,self.height =value
# else:
# self.__dict__[name] = value
# def __getattr__(self, name):
# if name == 'size':
# returnself.width,self.height
# else:
# raise AttributeError
# r = r()
# print(r.size)
# r.size = (100,120)
# print(r.height)
#
# class f:
# def __init__(self):
# self.a = 0
# self.b = 1
# def __next__(self):
# self.a,self.b =self.b,self.a+self.b
# return self.a
# def __iter__(self):
# return self
# f = f()
# for i in f:
# if i > 10000:
# print(i)
# break
#
# a = 0
# b = 1
# for i in range(10):
# a,b = b,a+b #这个语句很特别,同序不变赋值
# print(a)
# #注意和下文的区别;
# a = 0
# b = 1
# for i in range(10):
# a = b #顺序赋值
# b = a+b
# print(a)
#
# it = iter([1,2,3])
# print(next(it)) #迭代对象
# #到171页;
importos
# def caseScript():
#
# def __init__(self):
# self.name = 42
# # try:
# # f = open(r'D:\text.txt')
# #
# # except IOError:
# # print('脚本不存在,请更改预打开文件')
# # else:
# # while 1:
# # line = self.f.readline()
# # return line
# # if not line:
# # break
# # f.close()
# # finally:
# # print('welcom')
#
# a = caseScript()
# b = caseScript()
# print(b.name)
# print(testCase.f)
# def op():
#
# try:
# f = open(r'D:\text.txt')
# except IOError:
# print('脚本不存在,请更改预打开文件')
# else:
# while 1:
# line = f.readline()
# print(line)
# if not line:
# break
# f.close()
# finally:
# print('*****读文件完成*****')
# op()
# def f(n):
# if n == 1 or n == 2:
# s = 1
# else:
# s = f(n-2) + f(n-1)
# return s
# # print(f(10))
#
# def b(n):
# for i in range(n):
# a = 1
# b = 1
# a,b = b,a+b
# print(b(10))
# a = input('nums')
# for i in range(len(a)):
# if a[i] <= a[i+1]:
# temp = a[i]
# a[i] = a[i+1]
# a[i+1] = temp #python
# print(a)
#在下文的构造方法中;
# try:
# f = open(r'D:\text.txt')
#
# except IOError:
# print('脚本不存在,请更改预打开文件')
# else:
# while 1:
# line = f.readline()
# return line
# if not line:
# break
# f.close()
# finally:
# print('welcom') pass
# Traceback (most recent call last):
# File"C:/Users/yinzi/AutoTest/hanleScript.py", line 86, in <module>
# n = N(42)
# TypeError: __init__() should return None, not 'str' #上述代码报错,构造方法不支持读取文件输出的类型
# welcom
#############
#关于多继承构造方法初始化,以及构造方法返回None#
#############
# class N():
# def __init__(self,name):
# self.somevar = name
# print("pass")
# n = N(42)
# print(n.somevar)
#
# class M():
# def __init__(self,name1):
# self.anyvar = name1
# print("pass")
# m = M(43)
# print(m.anyvar)
#
# class B(N,M):
# def __init__(self):
# #如果子类要访问父类的初始属性,那么需要在子类的构造方法中重写父类的构造方法
# N.__init__(self,name = 42) #若父类构造方法有参数,则需要赋初始值
# super(B,self).__init__(name='12') #使用super函数同样需要赋初始值,多继承有参构造函数,无法调用super使用多个参数
# N.__init__(self,name = 42)
# M.__init__(self,name1 = '43')
# self.b = 'sec'
# print('B')
# b = B()
# print(b.somevar)
# print(b.anyvar)
# print(b.b)
# help(next)
#
# print(help.__doc__)
# a = set(range(10))
# print(a)
# b = 10
# a.add(b)
# print(a)
#
# set heap deque 集合,堆,双端队列
# time 时间
# import time
# a = time.asctime()
# print(a)
#
# import os
# import random
#
# x = random.random() #伪随机数
# y = random.getrandbits(15) #伪随机数
# z = random.SystemRandom(15) #相对随机数
# ran = os.urandom(1) #相对真随机数
# print(x,'\n',y,'\n',z)
# print(ran)
#
# #模拟发牌程序
# from pprint import pprint
# from random import shuffle
# values ='2 3 4 5 6 7 8 9 10 J Q K A'.split()
# sults = 'diamonds clubs hearts spades'.split()
# deck = [(v,s) for v in values for s in sults]
# shuffle(deck)
# # pprint(deck[:12])
#
# while deck:input(deck.pop())
#
# shelve
#
# s = 'uasdi;dnd1 283 01s]f[,'
# a = s.split()
# print(a) #结果为列表
# print(a[0],a[1],a[2])
# [ ] #list
# ( ) #tuple 元组
# { } #set 集合
# a = set() #集合只能用set()类来声明
# a1 = {} #此方式声明的为空字典,而不是空集合,需要留意;
# a.add(1)
# #a1.add(1) #报错,没有这种方法(字典没有add方法,可见不是字典)
# print(a)
#
# b = dict()
# b.__setitem__(1,3)
# b1 = {}
# b1.__setitem__(1,2)
# print(b,b1)
#
# c = list()
# c.append(1)
# c1 = []
# print(c,c1)
# c1.append(2)
#
#
# d = tuple()
# d1 = (1) #元组声明后元素,不可修改,即没有直接提供向元组增加元素的方法;
# d2 = (2)
# s = d2 + d1 #这是对元祖元素本身值的相加,并不是增加了元素
# print(d,d1,s)
# import subprocess
# subprocess.call("sjasjdjas\\"+str(print(123)),shell = True)
# subprocess.call('cmd.exe',shell = True)
#创建文件
# import time
# def File(filename):
# try:
# fullname =os.getcwd()+'\\'+filename+str(time.strftime("%H %M %S%MS")).replace(':','')+'.log'
# open(fullname,'w')
# except Exception as error:
# print(error)
# File('log')
# import gc
# x = 5
# y = 5
# print(id(x),id(y),id(5))
# del x,y
# print(id(5))
# print(gc.isenabled())
# # help(gc)
# #欲快速释放5占用的内存,需要调用gc模块
#import itertools itertools模块,比较重要:
# class testIterator:
# value = 0
# def __next__(self):
# self.value += 1
# if self.value > 10:
# raise StopIteration
# return self.value
# def __iter__(self):
# return self
# t1 = testIterator()
# print(list(t1))
# yield 函数 一次产生多个值,如果只产生一个,函数会被动結;
# nest = [[1,2],[2,3],[3,4]] #嵌套列表
# def cons(nest):
# for a in nest:
# for ele in a:
# yield ele #包含yield的块称为生成器。
# for num in cons(nest): #在生成器上迭代使用所有的值。
# print(num)
# print(list(cons(nest)))
# g = ((i+2)**2 for i in range(2,27)) #类似列表推导式[],在此定义为生成器推导式()
# print(g.__next__()) #输出为:<generator object <genexpr> at 0x018DBF00>#可以使用类似next的方法逐个访问,但经实践报错,无next属性;
# nest = [[1,2],[2,3],[3,4],2]
# def flat(nest):
# try:
# for list in nest:
# for element in flat(list):
# yield element
# except TypeError:
# yield nest
# print(list(flat(nest)))
# def flat(nest):
# try:
# nest+''
# except TypeError:
# pass
# else:
# raise TypeError
# for list in flat(nest):
# for ele in list:
# yield ele
# list = list(flat(['foo']))
# print(list) #报超越深度错误:RecursionError: maximum recursion depth exceeded while calling aPython object
# def repeat(value):
# while True:
# new = (yield value) #yield 表达式需要闭合,安全起见
# if new is None:
# value = new
# r = repeat(42)
# print(r.__next__())
# print(r.__next__())
# a = r.send('hello')
# print(a) #并没有输出hello,也就是说并没有挂起,仍然输出42,表示很...
#N皇后的递归程序,感觉不是很对;
# from itertools import*
# cols = range(17) #一个17皇后问题,n;计算效率颇低,建议后期考虑并行计算
# res = 0
# for vec in permutations(cols):
# if(17 == len(set(vec[i]+i for i incols)) == len(set(vec[i] - i for i in cols))):
# res += 1
# print(vec)
# print(res)
# 下面这个方法有问题,需要相关修改
# def nQueens(n,x=0,*solution):
# if x == n:
# yield solution
# else:
# for y in range(n):
# if all(y!=j andabs(x-i)!=abs(y-j)for i,j in solution):
# yield fromnQueens(n,x+1,*solution)
# print(nQueens(17))
# def queens(num,state):
# if(len(state)) == num-1:
# for pos in range(num):
# if not conflicts(state,pos):
# yield pos
# def conflicts(state,nextX):
# nextY = len(state) #state宽度 等于行数
# for i in range(nextY): # i和nextY为行数
# if abs(nextX - state[i]) in(0,nextY - i): # X 为列数
# return True
# return False
#
# def queens(num,state = ()):
# for pos in range(num):
# if not conflicts(state, pos):
# if(len(state) == num - 1):
# yield(pos,)
# else:
# for result inqueens(num,state + (pos,)):
# yield (pos,) +result
#
# # list = list(queens(4)) #列表化
# # print(list)
# #
# # count = 0
# # for solution in queens(8): #单一化
# # print(solution)
# # count += 1
# # print(count)
#
# def prettyprint(solution):
# def line(pos,length =len(solution)):
# return ' . ' * pos + ' O ' + '. ' * (length - pos - 1)
# for pos in solution:
# print(line(pos))
#
# import random
# prettyprint(random.choice(list(queens(4))))
#八皇后问题到此结束
# a = (1)
# b = (1,)
# print(a) #数字
# print(b) #逗号扩充元组
# import sys
# sys.path.append("")
# if __name__ == '__main__':
# pass
# assert("exe func()") #可选的单例执行模式和作为方法执行模式,常用于测试
# import copy
# help(copy)
# print(copy.__doc__)
# print(range.__doc__)
# print(set(range(10)))
# import time
# from random import*
# # print(time.asctime())
# # help(time)
#
# for i in range(6): a = randrange(4) + 6; print(a)
# import shelve
# s = shelve.open('text.txt')
# s['a'] = [1,2,3]
# s['a'].append(4) #shelve是对副本的操作,而非对象本身,使用后会立即失联
# s['a'] = s['a'].append(4) #输出为None,证明它不以自身为中间变量迭代对象
# print(s['a'])
#
# temp = s['a']
# temp.append(4)
# s['a'] = temp
# print(s['a'])
#re正则表达式:
# import re
# text = "alpha.beta... - - .gamma ? / delta"
# print(re.split('[. ]+',text)) #以任意长度的字符串和空格来分割字符串
#
# pat = r'[a-zA-Z]+'
# pat1 = r'[.?\-"\'\\\,]+' #二义性问题,转义
# t1 = re.findall(pat,text)
# t2 = re.findall(pat1,text)
# print(t1)
# print(t2)
#
# print(re.escape('www.python.org'))
# print(re.escape('But where is the ambiguity?')) #escape()
# www\.python\.org
#But\ where\ is\ the\ ambiguity\? 函数转义
# import re
# m = re.match(r'www\.(.*)\..{3}','www.python.org') #match从指定串的开头匹配;
# print(m)
# print(m.group(1))
# print(m.group(0))
# print(m.group(2)) # no such group
# pat = r'\*([^\*]+)\*' #贪心匹配模式
# pat2 = r'\*([^\*?]+)\*' #非贪心匹配模式
# print(re.sub(pat,r'<lib>\1</lib>','hello,*world*'))
#print(re.sub(pat,r'<lib>\1</lib>','hello,*world**danlei**Mrs.Z**!'))
# print('not greedy pat:')
# print(re.sub(pat2,r'<lib>\1</lib>','hello,*world*'))
#print(re.sub(pat2,r'<lib>\1</lib>','hello,*world**danlei**Mrs.Z*'))
# f = open('1.txt','a+')
#
# import sys
# text = sys.stdin.read()
# word = text.split()
# count = len(word)
# print(count)
# f = open(r'1.txt','w')
# f.write('01213213312r45454564')
# f.seek(5)
# f.write("hello")
# f.close()
# f = open(r'1.txt')
# print(f.read())
# print(f.readline(2))
# # print(f.read(3)) #无输出
# # print(f.read(2)) #无输出
# print(f.tell())
#
# with open('2.txt','a') as txt:
# pass #with语句自带文件关闭;
# f = open(r'1.txt','w')
# f.write('q1231231312312')
# f.close()
# f = open(r'1.txt')
# lines = f.readlines()
# f.close()
# #lines[1] = "isn't a\n" #提示越界,原因不明
# f = open(r'1.txt','w')
# f.writelines(lines)
# f.close()
# f = open(r'1.txt')
# while 1:
# char = f.read(1)
# print(char)
# if not char:
# break
# f.close() #按字符处理
# import fileinput #懒惰行迭代
# for line in fileinput.input(r'1.txt'):
# print(line)
# for line in open(r'1.txt'):
# print(line)
#
# import sys
# for line in sys.stdin:
# print(line)
# import socket
# import urllib
# s = socket.socket()
#
# # host = socket.gethostname()#z主机名无法解析,于是直接替换为ip地址
# host = "localhost"
# port = 1234
# s.bind((host,port))
# s.listen(10) #param相当于缓冲队列
# while 1:
# s.addr = s.accept()
# print("Got connectionfrom",s.addr)
# s.send('123+8+255')
# s.close()
# from urllib3 import urlopen
# webpage = urlopen('localhost')
# import urllib.request
# import re
# import urllib.error
# try:
# page = urllib.request.urlopen('http://localhost:8080/login?from=%2FNMS%2Flogin%3Bjsessionid%3DB5E3831D775F14F539E4962E52292CA1',timeout= 0.1)
# html = page.read()
# m = re.search('<a href ="([^"]+)".*?>about</a>',str(html),re.IGNORECASE)
# except urllib.error.URLError as e:
# ifisinstance(e.reason.socket.timeout):
# print('timeout')
#python与数据结构
# import math
# s = math.sqrt(16)
# print(s)
#
# print((5>=1)and(5<=10))
#
# a = [1,2,4]
# b = [1,2,3]
# print( a + b)
#
# mylist = [0] * 6
# print(mylist)
#
# mylist = a * 3
# print(mylist)
# A = [mylist] * 3
# print(A)
# mylist[2] = 45 #是对引用值的重复,而非数组本身的 2
# print(A)
# myList = [1024, 3, True, 6.5]
# myList.append(False)
# print(myList)
#
# myList.insert(2,4.5)
# print(myList)
#
# print(myList.pop())
# print(myList)
#
# print(myList.pop(1))
# print(myList)
#
# myList.pop(2)
# print(myList)
#
# myList.sort()
# print(myList)
#
# myList.reverse()
# print(myList)
#
# print(myList.count(6.5))
#
# print(myList.index(4.5))
#
# myList.remove(6.5)
# print(myList)
#
# del myList[0]
# print(myList)
#
# print((54).__add__(21))
# a = range(5,10,2)
# print(a)
# for i in a:
# print(i)
# print(list(a)) #列表化
#
# # 字符串是字符序列
#
# a = 'lix999'
# a = a.rjust(10) #字符串向右移位,扩展长度
# print(a,len(a))
#
# a = (1,2,3)
# print(a[2])
# a[2] = '15' #元组和字符串不支持对值的修改
# print('123','world',sep = '\n')
# print('%20.2fs is %20.2i years old'%(15,14)) #python由format函数也可实现;
#
# a = [1,2,3]
# b = list()
#
# for i in a:
# b.append(i)
# print(b)
#
# a = [x**3 for x in range(10)]
# print(a)
# class F:
# def __init__(self,t,b):
# self.num = t
# self.den = b
#
# def show(self):
# print(self.num,'/',self.den)
#
# def show2(a,b):
# print(a,'/',b)
#
# f = F(1,2)
# f.show = show2
# print(f.show(1,2)) #绑定外部方法;
# class LogicGate:
# def __init__(self,n):
# self.name = n
# self.output = None
# def getName(self):
# return self.name
# def getOutput(self):
# self.output =self.performGateLogic()
# return self.output
# class BinaryGate(LogicGate):
# def __init__(self,n):
# LogicGate.__init__(self,n)
# self.pinA = None
# self.pinB = None
# def getPinA(self):
# if self.pinA == None:
# returnint(input("Enter Pin A input for gate "+self.getName()+"-->"))
# else:
# returnself.pinA.getFrom().getOutput()
# def getPinB(self):
# if self.pinB == None:
# returnint(input("Enter Pin B input for gate"+self.getName()+"-->"))
# else:
# return self.pinB.getFrom().getOutput()
# import time
# from timeit import Timer
# def sum(n):
# return (n*(n+1))/2
# a = [pow(10,4),pow(10,5),pow(10,6),pow(10,7),pow(10,8)]
# for i in a:
# start = time.time()
# print(sum(i))
#
# t1 = Timer('sum(1000000)','from __main__ import sum')
# print('concat',t1.timeit(number = 1000),'ms')
#
# import timeit
# import random
#
# for i in range(10000,1000001,20000):
# t =timeit.Timer("random.randrange(%d) in x"%i,
# "from __main__ import random,x")
# x = list(range(i))
# lst_time = t.timeit(number=1000)
# x = {j:None for j in range(i)}
# d_time = t.timeit(number=1000)
# print("%d,%10.3f,%10.3f"% (i, lst_time, d_time))
#线性数据结构:stack,list,queue,Dqueue
#fifo//lifo 先进先出和后进先出
# class Quene: #用list实现的quene
# def __init__(self):
# self.items = []
#
# def isEmpty(self):
# return self.items == []
#
# def enquene(self,item):
# self.items.insert(0,item)
#
# def dequene(self):
# return self.items.pop()
#
# def size(self):
# return len(self.items)
#
# def item(self):
# for i in self.items:
# return i
#
# # q = Quene()
# #
# # q.enquene(4)
# # q.enquene('dog')
# # q.enquene(True)
# # print(q.size())
# # print(q.dequene())
# #
# # print(q.item())
#
# def hPotato(namelist,num):
# s = Quene()
# for name in namelist:
# s.enquene(name)
#
# while s.size() > 1:
# for i in range(num):
# s.enquene(s.dequene())
#
# s.dequene()
# return s.dequene()
# print(hPotato([1,2,3,4,5,6],7))
# #队列热土豆问题测试结束
#Dquene构造开始
# class Deque:
# def __init__(self):
# self.items = []
# def isEmpty(self):
# return self.items == []
# def addFont(self,item):
# self.items.append(item)
# def addRear(self,item):
# self.items.insert(0,item)
# def removeFont(self):
# return self.items.pop()
# def removeRear(self ):
# return self.items.pop(0)
# def size(self):
# return len(self.items)
#
# d = Deque()
# #print(d.isEmpty())
# #回文词判定
# def pcheck(str):
# cdeque = Deque()
# for ch in str:
# cdeque.addRear(ch)
# equal = True
#
# while cdeque.size() > 1 andequal:
# first = cdeque.removeFont()
# last = cdeque.removeRear() #每次取对称的两侧比较
#
# if first != last:
# equal = False
# return equal
# print(pcheck('asdasda'))
#双端队列构造以及回文词判定结束
#使用链表实现无序列表 使用相对位置来确定
# class Node: #节点类
# def __init__(self,initdata):
# self.data = initdata
# self.next = None
# def getData(self):
# return self.data
# def getNext(self):
# return self.next
# def setData(self,newdata):
# self.data = newdata
# def setNext(self,next):
# self.next = next
# # temp = Node(9)
# # print(temp.getData())
#
# class UnorderList: #无序列表
# def __init__(self):
# self.head = None
# def isEmpty(self):
# return self.head == None
#
# def add(self,item):
# temp = Node(item) #因为第一个被添加的元素到构造函数中初始化之后指向None,所以自然
# temp.setNext(self.head) #不自然的成为了最后一个数据
# self.head = temp
#
# def size(self):
# current = self.head
# count = 0
# while current != None:
# count = count + 1
# current = current.getNext()
# return count
#
# def search(self,item):
# current = self.head
# found = False
# while current!= None and notfound:
# if current.getData() ==item:
# found = True
# else:
# current =current.getNext()
# return found
#
# def remove(self,item): #错位移董实现替换
# current = self.head
# previous = None
# found = False
# while not found:
# if current.getData() ==item:
# found = True
# else:
# previous = current
# current =current.getNext()
#
# if previous == None:
# self.head = current.getNext()
# else:
# previous.setNext(current.getNext())
#
# #借助以上Node类来实现一个有序列表;
# class Orderlist:
# def __init__(self):
# self.head = None
#
# def search(self,item):
# current = self.head
# found = False
# stop = False
# while current != None and notfound and not stop:
# if current.getData() ==item:
# found = True
# else:
# if current.getData()> item:
# stop = True
# else:
# current =current.getNext()
# return found
#
# def add(self, item): #有序队列增加操作有待于继续研究
# current = self.head
# previous = None
# stop = False
# while current != None and notstop:
# if current.get_data() >item:
# stop = True
# else:
# previous = current
# current =current.get_next()
# temp = Node(item)
#
# if previous == None:
# temp.setNext(self.head)
# self.head = temp
# else:
# temp.setNext(current)
# previous.set_next(temp)
# def tostr(n,b):
# n = int(n)
# b = int(b)
#
# str = "0123456789ABCDEF"
# if n < b:
# return str[n]
# else:
# return tostr(n/b,b) + str[n %b]
# print(tostr(10,2))
# import turtle
# myTurtle = turtle.Turtle()
# myWin = turtle.Screen()
# # def drawSpiral(myTurtle, lineLen):
# # if lineLen > 0:
# # myTurtle.forward(lineLen)
# #
# # myTurtle.left(90)
# # drawSpiral(myTurtle,lineLen-10)
# # drawSpiral(myTurtle,300)
# # myWin.exitonclick()
# # turtle.done()
# t = turtle.Turtle()
# def tree(branchLen,t):
# if branchLen > 5:
# t.forward(branchLen)
# t.right(20)
# tree(branchLen-15,t)
# t.left(40)
# tree(branchLen-10,t)
# t.right(20)
# t.backward(branchLen)
# tree(100,t)
# myWin.exitonclick()
# turtle.done()
#
# import turtle
# def tree(branchLen,t):
# if branchLen > 5:
# t.forward(branchLen)
# t.right(20)
# tree(branchLen-15,t)
# t.left(40)
# tree(branchLen-15,t)
# t.right(20)
# t.backward(branchLen)
# def main():
# t = turtle.Turtle()
# myWin = turtle.Screen()
# t.left(90)
# t.up()
# t.backward(200)
# t.down()
# t.color("green")
# tree(100,t)
# myWin.exitonclick()
# main()
# help('turtle')
# import turtle
# t = turtle.Turtle()
# myWin = turtle.Screen()
#
# myWin.exitonclick()
# turtle.done()
# import turtle
# t = turtle.Turtle()
# myWin = turtle.Screen()
# # 设置初始位置
# t.penup()
# t.left(90)
# t.fd(200)
# t.pendown()
# t.right(90)
#
# # 花蕊
# t.fillcolor("red")
# t.begin_fill()
# t.circle(10,180)
# t.circle(25,110)
# t.left(50)
# t.circle(60,45)
# t.circle(20,170)
# t.right(24)
# t.fd(30)
# t.left(10)
# t.circle(30,110)
# t.fd(20)
# t.left(40)
# t.circle(90,70)
# t.circle(30,150)
# t.right(30)
# t.fd(15)
# t.circle(80,90)
# t.left(15)
# t.fd(45)
# t.right(165)
# t.fd(20)
# t.left(155)
# t.circle(150,80)
# t.left(50)
# t.circle(150,90)
# t.end_fill()
#
# # 花瓣1
# t.left(150)
# t.circle(-90,70)
# t.left(20)
# t.circle(75,105)
# t.setheading(60)
# t.circle(80,98)
# t.circle(-90,40)
#
# # 花瓣2
# t.left(180)
# t.circle(90,40)
# t.circle(-80,98)
# t.setheading(-83)
#
# # 叶子1
# t.fd(30)
# t.left(90)
# t.fd(25)
# t.left(45)
# t.fillcolor("green")
# t.begin_fill()
# t.circle(-80,90)
# t.right(90)
# t.circle(-80,90)
# t.end_fill()
#
# t.right(135)
# t.fd(60)
# t.left(180)
# t.fd(85)
# t.left(90)
# t.fd(80)
# # 叶子2
# t.right(90)
# t.right(45)
# t.fillcolor("green")
# t.begin_fill()
# t.circle(80,90)
# t.left(90)
# t.circle(80,90)
# t.end_fill()
#
# t.left(135)
# t.fd(60)
# t.left(180)
# t.fd(60)
# t.right(90)
# t.circle(200,80)
# import time
# time.sleep(2)
#
# t.penup()
# t.goto(180,44)
# t.color('orange')
# t.write("for:",font = ('Arial',30,'normal'))
# t.goto(240,-20)
# # t.color('violet')
# t.color('violet')
# t.write("......",font = ('Arial',40,'normal'))
# t.goto(160,-64)
# t.color('green')
# s = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
# t.write(str(s),font = ('Arial',20,'normal'))
#
# myWin.exitonclick()
# turtle.done()
# import turtle
# t = turtle.Turtle()
# myWin = turtle.Screen()
# t.speed(10)
# def draw(n):
# for i in range(5):
# t.forward(80)
# t.left(n)
# for i in range(15):
# draw(170)
# myWin.exitonclick()
# turtle.done()
# def moveTower(height,fromPole,toPole,withPole):
# if height >= 1:
# moveTower(height-1,fromPole,withPole,toPole)
# moveDisk(fromPole,toPole)
# moveTower(height-1,withPole,toPole,fromPole)
#
# def moveDisk(fp,tp):
# print('moving from',fp,'to',tp)
# moveTower(3,'A','B','C')
############################################
#对于汉诺塔问题解数量的求法:
#数学归纳法:
# f(1) = 1 f(2) = 3 f(3) = 7 f(n) = 2*f(n-1) + 1,求f(n)与n的关系;
# 当 n>2 时,f(n) = 2^(n-1) +1+ 2 +...+ 2^(n-2) = 2^n-1
#选择排序
# def selectionSort(alist):
# for fillslot inrange(len(alist)-1,0,-1): #(start,end,step) 可排序fillslot已饱和槽
# positionOfMax = 0
# for location inrange(1,fillslot + 1):
# if alist[location] >alist[positionOfMax]:
# positionOfMax =location
#
# temp = alist[fillslot]
# alist[fillslot] =alist[positionOfMax]
# alist[positionOfMax] = temp
#
# alist = [26,54,93,17,77,31,44,55,20]
# selectionSort(alist)
# print(alist)
# def FUNC(list):
# for i in range(len(list)-1,0):
# Maxpos = 0
#比较简洁精巧的插入排序
# def insertSort(list):
# for index in range(1,len(list)):
# pvalue = list[index] #把原来索引的数据先保存下来;
# while index > 0 and pvalue< list[index - 1]: #如果小于前面一个索引
# list[index] = list[index -1] #移动前面索引值的到当前
# index -= 1 #索引前移,索引
# list[index] = pvalue #视情况决定索引时否变化,未进入循环则不变,进如循环则变化
# print(list)
# print('last:',list)
# list = [54,26,93,17,77,31,44,55,20]
# insertSort(list)
#希尔排序 间隔分块后再执行 插排
#归并排序 递归拆分至原子列表,再合并
#快速排序 #堆排序 #桶排序 #基数排序
#树和树算法
# class BinaryTree:
# def __init__(self,rootObj):
# self.key = rootObj
# self.leftChild = None
# self.rightChild = None
#
# def insertLeft(self,newNode):
# if self.leftChild == None:
# self.leftChild =BinaryTree(newNode)
# else:
# t = BinaryTree(newNode)
# t.leftChild =self.leftChild #降级
# self.leftChild = t
# import wx
# app = wx.App()
# win = wx.Frame(None,title='MY WINDOW',size = (800,600))
# loadButton = wx.Button(win, label = '打开',pos =(225,5),size = (80,25))
# saveButton = wx.Button(win, label = '保存',pos =(315,5),size = (80,25))
# filename = wx.TextCtrl(win,pos = (5,5),size = (210,25))
# contents = wx.TextCtrl(win,pos = (5,35),size = (390,260),style =wx.TE_MULTILINE|wx.HSCROLL)
# win.Show()
# app.MainLoop()
#图 邻接矩阵(二维矩阵) 邻接表
#使用字典实现邻接表
# class Vertex:
# def __init__(self,key):
# self.id = key
# self.connectedTo = {}
# def addNeighbor(self,nbr,weight =0):
# self.connectedTo[nbr] = weight
# def __str__(self):
# return str(self.id) +'connectedTo' + str([x.id for x in self.connectedTo])
# def getConnections(self):
# return self.connectedTo.keys()
# def getId(self):
# return self.id
# def getWeight(self,nbr):
# return self.connectedTo[nbr]
#
# class Graph:
# def __init__(self):
# self.vertList = {}
# self.numVertices = 0
# def addVertex(self,key):
# self.numVertices =self.numVertices + 1
# newVertex = Vertex(key)
# self.vertList[key] = newVertex
# return newVertex
# def getVertex(self,n):
# if n in self.vertList:
# return self.vertList[n]
# else:
# return None
# def __contains__(self,n):
# return n in self.vertList
# def addEdge(self,f,t,cost=0):
# if f not in self.vertList:
# nv = self.addVertex(f)
# if t not in self.vertList:
# nv = self.addVertex(t)
# self.vertList[f].addNeighbor(self.vertList[t],cost)
# def getVertices(self):
# return self.vertList.keys()
# def __iter__(self):
# returniter(self.vertList.values())
#####################图实现结束#######################
#print('x'+'y')
class a:
def a(self,b):
self.b = 5
print(self.b)
class b(a):
def b(self):
print(123)
class c(b):
def c(self):
print(456)
A = a()
A.a(15)
c = c()
c.a(15) #在JAVA中,继承和接口对方法的调用也是传递的,但C继承B,B继承A,并不等同于
# 多继承C继承 A,B对于接口而言,A实现了某个接口,B继承了A,C继承了B,那么C的实例可
# 以调用A的方法;而A,和 B都实现了某个接口但实现方法不同,,而B继承自A,C继承自B,会
# 以最新覆盖的为准;所以多继承和传递继承的区别在于,每个派生类只有一个基类和一个派生
#类有多个同等地位的父类(虽然也存在着方法的覆盖(比如python是先入为主,只是具备写在前面基类的属性))
这些都更加反映了python对象一旦建立,则具有不可变性,在这里有人肯定说list可以被修改,但实际上list作为数据结构中的链式表,是通过指针来维系的,可以修改是因为修改了尾指针指向了新的内存块,并通知上一个元素的指针指向新增内存,对对象内容进行修改和对象是否具有可变性不冲突、不矛盾,两者是不同的概念。