from functools import reduce
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError("输入数据不合格!")
if x>0:
return x
else:
return -x
print(my_abs(-1))
print(my_abs(int("0")))
def power(x,n):
s=1
while(n>0):
s=s*x
n=n-1
return s
print(power(5,2),power(3,3))
def inname(name,score):
print("name:",name)
print("score:",score)
inname("xwq",100)
#最后一行的结果为['end','end']
def ab(L=[]):
L.append("end")
return L
print(ab(['xwq','love','tyl']))
print(ab())
print(ab())
#避免多次出现'end'的现象, 定义默认参数要牢记一点:默认参数必须指向不变对象!(str,None)
def abb(L=None):
if L is None:
L=[]
else:
L.append("end")
return L
print(abb())
print(abb())
def powern(number):
sum=0
for q in number:
sum=sum+q*q
return sum
print(powern([1,2,3]))
print(powern((3,4,5)))
def pf(L=[]):
sum=0
for n in L:
sum=sum+n*n
return sum
print(pf([1,2,3,4]))
#接收到的是一个元组
def pfh(*nums):
sum=0
for n in nums:
sum=sum+n*n
return sum
print(pfh(2,3,4))
def pfh1(*nums):
sum=0
for n in nums:
sum=sum+n*n
return sum
nums=[1,2,3]
print(pfh1(*nums))
#年龄和姓名是必选项,其他是可选项,可应用于用户注册界面,kw可传入字典
def person(name,age,**kw):
print('name:',name,'age:',age,'other:',kw)
person('徐文强',21,city='咸阳')
person('同艳丽',22,chact='love xwq',city='weinan')
extra={'city':'beijing','chact':'nicai'}
person('xiaohong',23,**extra)
def person1(name,age,**kw):
if 'city' in kw:
pass
if 'job' in kw:
pass
print('name:',name,'age:',age,'other:',kw)
person1('xt',23,job='gcs',city='xa')
person1('xt',24)
#函数定义的参数定义有:必选参数、默认参数、可变参数、关键字参数和命名关键字参数,顺序为:必选参数、默认参数、可变参数、命名关键字参数(*)(必须传入关键字)和关键字参数(**)。
def p1(name,age,*args,city,job):
print(name,age,args,city,job)
p1('xt',23,city='beijing',job='gcs')
#*args是可变参数,args接收的是一个tuple;
#**kw是关键字参数,kw接收的是一个dict。
#以及调用函数时如何传入可变参数和关键字参数的语法:
#可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过*args传入:func(*(1, 2, 3));
#关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过**kw传入:func(**{'a': 1, 'b': 2})。
#使用*args和**kw是Python的习惯写法,当然也可以用其他参数名,但最好使用习惯用法。
#命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。
#定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数。
def print_scores(**kw):
print(' Name Score')
print('------------------')
for name, score in kw.items():
print('%10s %d' % (name, score))
print()
print_scores(Adam=99, Lisa=88, Bart=77)
data = {
'Adam Lee': 99,
'Lisa S': 88,
'F.Bart': 77
}
print_scores(**data)
def print_info(name, *, gender, city='Beijing', age):
print('Personal Info')
print('---------------')
print(' Name: %s' % name)
print(' Gender: %s' % gender)
print(' City: %s' % city)
print(' Age: %s' % age)
print()
print_info('Bob', gender='male', age=20)
print_info('Lisa', gender='female', city='Shanghai', age=18)
def p2(**kw):
print('name score')
for name,score in kw.items():
print(name,' ',score)
print('---------')
p2(xuwenqiang=100,tongyanli=100)
def faction1(n):
if n==1:
return 1
return n*faction1(n-1)
print(faction1(3))
print('----------------')
def fact(n):
return fact_iter(n,1)
def fact_iter(num,product):
if num==1:
return product
return fact_iter(num-1,num*product)
print(fact(5))
L=['xu','tong','xt']
r=[]
n=3
for i in range(n):
r.append(L[i])
print(r)
def scrm(s):
if len(s)==0:
return s
elif s[0]==' ':
return (scrm(s[1:]))
elif s[-1]==' ':
return (scrm(s[:-1]))
return s
print(scrm(' hello '))
def fib(max):
n,a,b=0,0,1
while n<max:
print(b)
a,b=b,a+b
n=n+1
print(fib(9))
#杨辉三角 generator函数的’调用‘实际上返回的是generator对象
def yh():
L=[1]
while(True):
b=L.copy()
yield b
L.append(0)
L=[L[i]+L[i-1] for i in range(len(L))]
#可以直接作用于for的数据类型有以下几种,如list、tuple、dict、set、str等,一类是generator,包括生成器和带yield的函数。这些统称为可迭代对象,虽然list\dict\str是可迭代对象,但并不是迭代器,可用iter函数将其转化为迭代器(迭代器就是可以调用next()函数
#python 中的for循环本质上就是不断通过next()来实现的(Interator本质上就是一个惰性,只有在需要的时候才会去取下一个数据)
L='xuwenqiang'
for i in L:
print(i)
#函数式编程
def add1(a,b,f):
return f(a)+f(b)
c=add1(-7,-8,abs)
print(c)
#map函数接受2个参数,一个是函数,一个是可迭代的对象,作用就是将函数作用于每一个可迭代的数据上
def f(x):
return x*x
L=range(0,7)
r=map(f,L)
p=map(f,[1,2,3,4])
print(list(r))
print(list(p))
#reduce函数也是接受2个参数,可以实现累积,累加的效果
def zs(x,y):
return x*10+y
d=reduce(zs,[1,3,5,7])
print(d)
from functools import reduce
def fn(x,y):
return x*10+y
def char2num(s):
digitals={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
return digitals[s]
print(reduce(fn,map(char2num,'13579')))
Digitals={'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}
def str2int(s):
def fn1(x,y):
return x*10+y
def str2num(s):
return Digitals[s]
return reduce(fn1,map(str2num,s))
print(str2int('23456789'))
def s2i(s):
return Digitals[s]
def s2i1(s):
return reduce(lambda x,y:x*10+y,map(s2i,s))
#title()将字符串的第一个字母大写,其余小写
def normalsize(name):
return name.title()
print(normalsize('xuwenqianghetongyanli'))
def na1(name):
name1=name.lower()
name2=name1[0].upper()+name1[1:]
return name2
print(na1('xt'))
def mul(x,y):
return x*y
def qj(L):
return reduce(mul,L)
print(qj([1,2,3,4]))
def qj2(L):
return reduce(lambda x,y:x*y ,L)
print(qj2([2,3,4,5]))
#将字符串转换为浮点数
def str2double(s):
def getss(s):
digital={'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}
return digital[s]
radio=pow(10,len(s)-s.index('.')-1)
s=s.replace('.','')
return reduce(lambda x,y:x*10+y,map(getss,s))/radio
print(str2double('123.45678'))
def is_odd(n):
return n%2==1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9])))
a='aabs dfg rkeskjddaui'
print(a.strip('absi'))
print(a.lstrip('abs'))
print(a.rstrip('iu'))
print(a.strip())
#filter过滤序列,返回的是一个iterator,是惰性的,要返回全部的值,需要用list()获得所有结果并返回list
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty,['1','2',None,''])))
#筛选出素数(埃氏算法)
#先初始化出一些奇数
def is_odd():
n=1
while True:
n=n+2
yield n
#判断是否能被除尽
def not_division(n):
return lambda x:x%n>0
#获取素数
def prim():
yield 2
it=is_odd()
while True:
n=next(it)
yield n
it=filter(not_division(n),it)
for i in prim():
if i<1000:
print(i)
else:
break
s='abcdefghijklmn'
b=s[::-1]
print(b)
print(sorted(['Xuwenqiang','tongyanli']))
print(sorted(['xuwenqiang','Tongyanli'],key=str.lower,reverse=True))
print(sorted(['xuwenqiang','Tongyanli']))
#求和
def getsum(*args):
a=0
for n in args:
a=a+n
return a
m=[1,2,3,4]
print(getsum(*m))
def getsum1(*args):
def getsum2():
a=0
for n in args:
a=a+n
return a
return getsum2
n=(1,2,3,4,5,6)
f=getsum1(*n)
print(f())
f1=getsum1(2,4,6,8)
f2=getsum1(2,4,6,8)
print(f1())
print(f2())
print(f1==f2)
def count():
fs=[]
for i in range(1,5):
def f():
return i*i
fs.append(f)
return fs
f3,f4,f5,f6=count()
print(f3(),f4(),f5(),f6())
def count1():
fs=[]
def f(j):
def g():
return j*j
return g
for i in range(1,4):
fs.append(f(i))
return fs
f3,f4,f5=count1()
print(f3(),f4(),f5())
def cou():
a=[0]
def coun():
a[0]=a[0]+1
return a[0]
return coun
print(cou())
def log(fun):
#wrapper的参数是*args,**kw,因此可以接受任意参数的调用
def wrapper(*args,**kw):
print('call %s():'%fun.__name__)
return fun(*args,**kw)
return wrapper
@log
def now():
print('2021-09-05')
now()
def hi(name='xt'):
return 'hi'+name
print(hi('xiaotong'))
h1=hi
print(h1())
del hi
print(h1())
def hi1():
return "hi yasoob!"
def doSomethingBeforeHi(func):
print("I am doing some boring work before executing hi()")
print(func())
doSomethingBeforeHi(hi1)
def hh(name='xuwenqiang'):
def wel():
return 'now you are in welcome()'
def greet():
return 'now you are in greet()'
if name=='xuwenqiang':
return greet
else:
return wel
tyl=hh()
print(tyl())
from functools import wraps
def a(c_func):
@wraps(c_func)
def b():
print('before exe function')
c_func()
print('after exe function')
return b
@a # @a相当于c_func=a(c_func)
def c_func():
print('i am the function')
c_func()
print(c_func.__name__)
def func(f):
@wraps(f)
def decorater(*args,**kw):
if not can_run:
return 'can\'t run'
return f(*args,**kw)
return decorater
@func
def output():
return ('i am running')
can_run=True
print(output())
can_run=False
print(output())
print(output.__name__)
#装饰器的应用一:授权问题
def require_auth(f):
@wraps(f)
def decorated(*args,**kw):
auth=request.authorization
if not auth or not check_auth(auther.name,auther.password):
authenticate()
return f(*args,**kw)
return decorated
py_基础
最新推荐文章于 2022-08-26 16:30:31 发布