python的函数式编程 和 面向对象

(1)
def add(a,b):
    c=a+b
    return c
c=add(1,2)
x=add
y=add
add=1
x=1

(2)
a=print
print(a)
print(1)
print(print)

(3)
print(123)
a=print('asdasd')
print(a)

(4)
print(None)
print(print(1))
print(1)
print(1,2,3)
print(print(1),print(2))
print('123')
print(123)

(5)
def mul(a,b):
    return a*b

def square(x,x):
    return mul(x,x)

a=square(square(3))

(6)
def increase(n,k=1):
    return n+k

n=1
print(n)
n=increase(n)
print(n)
n=increase(n,2)
print(n)

(7)
from math import pi
def sum(a,b,c=2):
	return a+b+c
	
def add(a,b):
	return a+b

(8)质因数分解

证明:正整数n 除了n 之外的最小因数一定是质数

反证:

假设k 是n 除了1 之外的最小因数,且k 是合数,则:

k=p*q(p\not=1,q\not=1),则

p|k,q|k

由于k 是n 的因数,则:

k|n

所以 p|n ,p<k

即存在比k 还小的因数,和假设矛盾,故原命题成立

数学符号“∣”的意义,如a∣b:

'|'为整除符号,对于整数a,b(a≠0),

若存在整数k,使b=ka,则称a整除b,或b能被a整除,记为a∣b

整除具有传递性:

a|k,k|n,则a|n

def prime_fractorization(n):
    i=2
    while n!=1:
        if n%i==0:
            print(i)
            n=n//i
        else:
            i=i+1

(9)斐波那契数列
def fib(n):
    pred,curr=0,1
    while n>1:
        pred,curr=curr,pred+curr
        n-=1
    return curr
fib(n)

(10)泛化设计
from math import pi,sqrt
def area_square(r):
    return r*r*1
def area_circle(r):
    return r*r*pi
def area_hexagon(r):
    return r*r*3*sqrt(3)/2 # 六边形
def area(r,shape_constant):
   	assert r>0
    return r*r*shape_constant
def square(r):
    return area(r,1)
def circle(r):
    return area(r,pi)
def hexagon(r):
    return area(r,3*sqrt(3)/2)

$\frac{1}{2}r*\frac{\sqrt{3}}{2}r*6 $

(11)高阶函数
def sum_naturals(n):
    res,i=0,1
    while(i<n):
        res+=i
        i+=res
    return res
def sum_cubes(n):
    res,i=0,1
    while i<=n:
        res+=i*i*i
       	i+=1
    return res
def mul(x,y):
    return x*y
# 泛化
def natural(i):
    return i
def cube(i):
    return i*i*i
def split_term(i):
    return 8/mul(4*i-3,4*i-1)
def summation(n,term):
    res,i=0,1
    while i<=n:
        res+=term(i)
        i+=1
   	return res

(12)函数为返回值
def make_adder(n):
    def adder(k):
        return n+k
 	return adder
add_three=make_adder(3)
x=add_three(4)
y=make_adder(4)(8)

(13)匿名函数
func=lambda a,b:a+b
(14)控制语句
def condition():
    print('This is condition.')
    return True
def if_suite():
    print('This is if suite.')
def else_suite():
    print('This is else suite.')
def if_(condition_value,if_value,else_value):
    if condition_value:
   		return if_value
    else:
        return else_value
def if_statement():
    if condition():
        if_suite()
    else:
        else_suite()
def if_function():
    if_(condition(),if_suite(),else_suite())

(15)复合函数
def square(x):
    return x*x

def make_adder(n):
	def adder(k):
        return n+k
    return adder

def composel(f,g):
    def h(x):
        return f(g(x))
  	return h

composel(square,make_adder(2))(3)
(16)自引用
def print_sums(n):
    print(n)
    def next_sum(k):
        return print_sums(n+k)
  	return next_sum
print_sums(1)(3)(5)

(17)函数颗粒化
def make_adder(n):
    return lambda k:n+k

def add(x,y,z):
    return x+y+z
def make_adder_adder(x):
    def make_adder(y):
        def adder(z):
            return x+y+z
        return adder
    return make_adder
b=make_adder_adder(1)(2)(3)
add=lambda x,y,z:x+y+z
make_adder_adder=lambda x:lambda y: lambda z:x+y+z
make_adder_adder(1)(2)(3)
def f(x,y):
	def g(a):
        return a+y
    return g(x)
result=f(1,2)

(18)函数抽象
def mul(a,b):
    return a*b
def square(x):
    return mul(x,x)
def sum_squares(x,y):
    return square(x)+square(y)
(19)命名
def square(x):
    return pow(x,2)

def square(x):
    return mul(x,x-1)+x
x=(-b+sqrt(square(b)-4*a*c))/(2*a)
discriminant=square(b)-4*a*c
x1=(-b+sqrt(discriminant))/(2*a)

(20)递归
def sum_digits_rec(n):
    if n<10:
        return n
    former,last=n//10,n%10
    return sum_digits_rec(former)+last
# 迭代
def factor(n):
    if n==1:
        return 1
    return n*factor(n-1)
# 递归
def fact_iter(n):
    total,k=1,1
    while k<=n:
        total,k=total*k,k+1
    return total
(21)相互递归
def is_even(n):
    if n==0:
        return True
    return is_odd(n-1)
def is_odd(n):
    if n==0:
        return False
    return is_even(n-1)

(22)迭代和递归
# 迭代
def sum_digits_iter(n):
    digit_sum=0
    while n>0:
        n,last=split(n)
        digit_sum=digit_sum+last
   	return digit_sum
# 递归
def sum_digits_rec(n,digit_sum):
    if n==0:
        return digit_sum
    else:
        n,last=split(n)
        return sum_digits_rec(n,digit_sum+last)

(23)树形递归
def cascade(n):
    if n<10:
        print(n)
    else:
        print(n)
        cascade(n//10)
        print(n)
def grow(n):
    if n==0:
        return 
   	grow(n//10)
    print(n)
def shrink(n):
    if n==0:
        return
    print(n)
    shrink(n//10)
def inverse_cascade(n):
    grow(n//10)
    print(n)
    shrink(n//10)
def fib(n):
    if n==0:
        return 0
   	if n==1:
        return 1
    return fib(n-1)+fib(n-2)
(24)汉诺塔
def print_move(origin,destination):
    print('Move to top disk from rod',origin,"to rod",destination)
def move_stack(n,start,end):
    assert 1<=start<=3 and 1<=end<=3 and start!=end
    if n==1:
        print_move(start,end)
    else:
        bridge=6-start-end
        move_stack(n-1,start,bridge)
        print_move(start,end)
        move_stack(n-1,bridge,end)

(25)划分计数

def count_partitions(n,m):
	if n==0:
        return 1
   	elif n<0:
        return 0
    elif m==0:
        return 0
    else:
        with_m=count_partitions(n-m,m)
        without_m=count_partitions(n,m-1)
        return 

(26)List
digits=[1,8,2,8]
len(digits)
digits[3]
[2,7]+digits*2
pairs=[[10,20],[30,40]]
pairs[1]
pairs[1][0]
digits=[2//2,2+2+2+2,2,2*2*2]
getitem(digits,3)
add([2,7],mul(digits,2))

(27)容器
digits=[1,8,2,8]
a=1 in digits
b=8 in digits
c=5 not in digits
not(5 in digits)
def count(s,value):
    total=0
    for element in s:
        if element==value:
            total=total+1
    return total

(28)range
range(1,2)
range
list
list(range(1,2))
list(range(1,3))
list(range(2,10,2))
list(range(10))
(29)list 求和
# 迭代
def sum_iter(lst):
    total=0
    for ele in lst:
        total+=ele
    return total
# 递归
def sum_rec(lst):
    if len(lst)==0:
        return 0
   	return lst[0]+sum_rec(lst[1:0])

(30)列表映射表达式
t=[i for i in natural if i%2==0]
print(t)
natural=[1,2,3,4,5,6,7,9]
odd=[i for i in natural if i%2==1]
even=[i for i in natural if i%2==0]

(31)字符串
s='abaaba'
s
s[0]
s[2]
s[0:3]
a+'21123'
a=[1,2,3,4]
a[0]
a[-1]
(32)字符串翻转
# 迭代
def reverse_string_iter(s):
    res=''
    for i in s:
        res=i+res
# 递归   
def reverse_string_rec(s):
    if len(s)==0:
        return s
    return reverse_string_rec(s[1:0])+s[0]

(33)数据抽象,选择子和构造子
# 有理数
def rational(n,d):
    n,d=n//gcd(n,d),d//gcd(n,d)
    return [n,d]

# 分子 :numberator
def numer(x):
    return x[0]
# 分母 :denominator
def denom(x):
    return x[1]
# 加法 
def add_rational(x,y):
    nx,dx=numer(x),denom(x)
    ny,dy=numer(y),denom(y)
    return rational(nx*dy+ny*dx,dx*dy)
# 乘法
def mul_rational(x,y):
    return rational(numer(x)*number(y),denom(x)*denom(y))

# 判断相等
def equal_rational(x,y):
    return numer(x)*denom(y)==numer(y)*denom(x)

# 打印分数
def print_rational(x):
    print(numer(x),'/',denom(x))
(34)数对二元组
pair=[1,2]
x,y=pair

pair[0]
pair[1]
getitem(pair,0)
getitem(pair,1)
def pair(first,second):
    def pair_func(selector):
        if selector=='first':
            return first
        if selector=='second':
            return second
    return pair_func
	
def first(p):
    return p('first')

def second(p):
    return p('second')
(35)抽象屏障
add_rational([1,2],[1,4])
def divide_rational(x,y):
    return [x[0]*y[1],x[1]*y[0]]
def rational(n,d):
    g=gcd(n,d)
    n,d=n//g,d//g
    def rational_func(selector):
        if selector=='n':
            return n
        if selector=='d':
            return d
    return rational_func

def numer(x):
    return x['n']

def denom(x):
    return x['d']
(36)字典
me={'name':'bone','age':19,'gender':'male'}
print(me)
me['name']
me['age']
me['name']='hdbone'
me.keys()
me.values()
del me['hobby']
(37)盒子和箭头表示法
pair=[1,2]
nested_list=[[1,2],[],
            [[3,False,None],
            [4, lambda :5]]]
(38)切片
digits=[1,8,2,8]
start=digits[:1]
middle=digits[1:3]
end=digits[2:]
full=digits[:]
a=[1,2,3,4,5,6]
b=max(a,key=lambda x:-x)
a=[[1,2,3],[],[1],[-3,4,5,8]]
def max(lst,key=lambda x:x):
	res=lst[0]
    for ele in lst:
        if key(ele)>key(res):
            res=ele
    return res
b=max(a,key=lambda x:len(x))
(39)树
# 结构
def tree(label,branches=[]):
    for b in branches:
    	assert is_tree(b)
    return [label]+list(branches)
# 判断是否为一个树
def is_tree(t):
    if type(t)!=list or len(t)<1:
        return False
    for b in branches:
        if not is_tree(t):
            return False
    return True
# 节点分支
def branches(t):
    return t[1:]
# 节点的标签
def label(t):
    return t[0]
# 判断是否为叶子
def is_leaf(tree):
	return not branches(tree)
# 统计叶子的数量
def count_leaves(t):
    if is_leaf(t):
        return 1
   	else:
        branches_counts=[count_leaves(b) for b in branches(t)]
        return sum(branch_counts)
# 找出树的所有叶子
def leaves(t):
	if is_leaf(t):
        return [label(t)]
    else:
        return sum([leaves(b) for b in branches(t)],[])
# 复制一个树
def copy_tree(t):
    if is_leaf(t):
        return tree(label(t))
    return tree(label(t),[copy_tree(b) for b in branches(t)])
# 叶子 label+1
def increment_leaves(t):
    if is_leaf(t):
        return tree(label(t)+1)
    else:
        bs=[increment_leaves(b) for b in branches(t)]
        return tree(label(t),bs)
# 所有label +1
def increment(t):
    return tree(label(t)+1,[increment(b) for b in branches(t)])
# 打印树
def print_tree(t,indent=0):
    print('	'*indent+str(label(t)))
    for b in branches(t):
        print(b,indent+1)
# 路径集合
def sum_paths(t):
    if is_leaf(t):
        return [[label(t)]]
    res=[]
    for b in branches(t):
        paths=sum_paths(b)
        for p in paths:
	        res.append([label(t)]+p)

(40)type
def add(a,b):
    return a+b
type(add)
min
add
type
type(min)
type([1,2,3])
int
list
type(list)
type(1)
type(int)
(41)类
#include <cstdio>
#include <cstdlib.h>
using namespace std;

struct Dog{
    int size;
    char color[20];
}
void bark(Dog* this){
    if (this->size<20)
    {
		printf("%s Dog: Wuwuwu!\n",this->color);
    } else{
        printf("%s Dog: Woooooooof\n",this->color);
    }
}
Dog* makeDog(int size,const char* color)
{
	Dog* this=(Dog*)malloc(sizeof(Dog));
    this->size=size;
    strcpy(this->color,color);
    return this;
}
void delete(Dog* this)
{
	free(this);
}
int main()
{
    Dog* smallDog=makeDog(5,"Dark");
    Dog* bigDog=makeDog(20,"White");
    bark(smallDog);
    bark(bigDog);
    delete(smallDog);
    delete(bigDog);
    return 0;
}
(42)相等
[1,2,3]==[1,2,3]
[1,2,3] is [1,2,3]
1==1
1 is 1
1.1==1.1
type(1.1)
a=[1,2,3]
b=a
a==b
a is b
a=[10]
b=a
a==b
a.append(20)
a
b
a==b
a=[10]
b=[10]
a==b
b.append(20)
a
b
a==b
(43)修改性函数(先存后取)
def make_withdraw(balance):
    def withdraw(amount):
       	nonlocal balance
        if amount>balance:
            return 'Insufficient funds'
        balance=balance-amount
        return balance
    return withdraw
withdraw=make_withdraw(100)
print(withdraw(25))
print(withdraw(25))
print(withdraw(60))
print(withdraw(15))
(44)非本地赋值
def make_withdraw_list(balance):
    b=balance
    def withdraw(amount):
        if amount>b:
            return 'Insufficient funds'
        b=b-amount
        return b
    return withdraw
withdraw=make_withdraw_list(100)
print(withdraw(25))
print(withdraw(25))
print(withdraw(60))
print(withdraw(15))
# 报错
def make_withdraw_list(balance):
    b=[balance]
    def withdraw(amount):
        if amount>b[0]:
            return 'Insufficient funds'
        b[0]=b[0]-amount
        return b[0]
    return withdraw
withdraw=make_withdraw_list(100)
print(withdraw(25))
print(withdraw(25))
print(withdraw(60))
print(withdraw(15))
# 正确

(45)引用透明性
def f(x):
    x=4
    def g(y):
        def h(z):
            nonlocal x
            x=x+1
            return x+y+z
      	return h
    return g
a=f(1)
b=a(2)
c=b(3)+b(4)
(46)迭代器
s=[1,2,3,4]
it=iter(s)
it
next
next(it)
next(it)
d={'one':1,'two':2,'three':3}
d['zero']=0
k=iter(d.keys())
next(k)
next(k)
v=iter(d.values())
next(v)
next(v)
i=iter(d.items())
next(i)
next(i)
(47)for 语句的本质
# 倒数
class Countdown:
    def __init__(self,start):
        self.start=start
    def __iter__(self):
        v=self.start
        while v>0:
            yield v
            v-=1
a=Countdown(5)
for x in Countdown(6):
    print(x)
for x in a:
    print(x)
(48)迭代器函数
l=['b','c','d']
L=list(map(lambda x:x.upper(),l))
it =iter(range(2,4))
next(it)
list(filter(lambda x:x%2==1,[1,2,3,4,5]))
list(zip([1,2,3,4],[5,6,7,8]))
for x,y in zip([1,2,3],[4,5,6]):
    print(x,y)
it=reversed([1,2,3])
next(it)
next(it)
sorted([1,3,2,7,2])
(49)生成子
def plus_minus(x):
    yield x
    yield -x
t=plus_minus(3)
next(t)
next(t)
def countdown(k):
    if k>0:
        yield k
        yield from countdown(k-1)
def a_then_b(a,b):
    for x in a:
        yield x
    for x in b:
        yield x
def a_then_b(a,b):
    yield from a
    yield from b
list(a_then_b([3,4],[5,6]))
def countdown(n):
	if n==1:
        yield 1
    else:
        yield 
(50)面向对象
class Account:
    interest=0.02
    def __init__(self,account_holder):
        self.holder=account_holder
        self.balance=0
    def deposit(self,amount)
    	self.balance+=amount
        return self.balance
    def withdraw(self,amount):
        if amount>self.balance:
            return 'Insufficient funds'
        self.balance-=amount
       	return self.balance
account=Account('Tom')
account.deposit(100)
getattr(a,'holder')
getattr(a,'balance')
getattr(a,'deposit')
type(Account.deposit)
type(account.deposit)
Account.deposit(account,1001)
account.deposit(1004)
a.holder
a.balance
a.interest
Account.deposit
Account.withdraw
lambda amount:deposit(a,amount)(10)
(51)属性赋值
a=Account('John')
a.deposit(100)
print(a.interest)
a.interest=0.08
print(a.interest)
print(Account.interest)
Account.test='lalala'
Account.info=lambda self:self.holder+" "+str(self.balance)
print(a.info())
(52)继承
class CheckingAccount(Account):
    interest=0.01
    withdraw_fee=1
    def withdraw(self,amount):
        return Account.withdraw(self,amount+self.withdraw_free)
ch=CheckingAccount('Tom')
print(ch.interest)
print(ch.deposit(20))
print(ch.withdraw(5))
(53)属性查找
class A:
    z=-1
    def f(self,x):
        return B(x-1)
    
class B(A):
    n=4
    def __init__(self,y):
        if y:
            self.z=self.f(y)
        else:
            self.z=C(y+1)
class C(B):
    def f(self,x):
        return x
a=A()
b=B(1)
b.n=5
C(2).n
a.z==C.z
a.z==b.z
(54)多继承
class SavingAccount(Account):
    deposit_fee=2
    def deposit(self,amount):
        return Account.deposit(self,amount-self.deposit_fee)
    
class AsSeenOnTVAccount(CheckingAccount,SavingAccount):
    def __init__(self,acount_holder):
        self.holder=account_holder
        self.balance=1
(55)repr 和 eval
from operator import add
c=[1,2,3]
from fractions import Fraction
half=Fraction(1,2)
half
Fraction(1,2)
str(half)
repr(half)
a=Fraction(1,2)
a
eval
eval(a)
eval('a')
eval('Fraction(1,2)')
eval('1+2')
repr(half)
eval(repr(half))
str(eval(repr(half)))
half.__repr__()
half.__str__()
str(half)
type(half)
type(half).__repr__
type(half).__repr(half)
half.__repr__=1 # read-only
def repr(x):
    return x.__repr__(x)
def repr(x):
    return x.__repr__()
def repr(x):
    return type(x).__repr__(x)
def repr(x):
    return type(x).__repr__()
def repr(x):
    return super(x).__repr__()
repr
str
str(1)
str.__init__
def _repr(x):
	s=type(x).__repr__(x)
    if not isinstance(s,str):
        raise TypeError
    return s

def _str(x):
    s=type(x).__str__(x)
    if not isinstance(s,str):
        raise TypeError
    return s
(56)特殊方法名
zero,one,tow=0,1,2
one+two
bool(zero),bool(one)
zero,one,two=0,1,2
one.__add__(two)
zero.__bool__(),one.__bool__()
class A:
    def __init__(self):
        self.__repr__=lambda: 'instance A repr'
        self.__str__=lambda: 'instance A str'
    def __repr__(self):
      	return 'A()'
    def __str__(self):
        return 'a'
    def __bool__(self):
        return False
from fractions import gcd
class Ration:
    def __init__(self,n,d):
        self.numer=n
        self.denom=d
    def __repr__(self):
        return 'Ratio({0},{1})'.format(self.numer,self.denom)
    def __str__(self):
        return self.numer/self.denom
    def __float(self):
        return self.numer/self.denom
    def __add__(self):
        if isinstance(self,other):
            n=self.numer*other.denom+other.numer+self.denom
            d=self.denom*other.denom
        elif isinstance(other,int):
            return float(self)+other
       	g=gcd(n,d)
        return Ration(n//g,d//g)
Ration(1,3)+1
1+Ration(1,3)
from math import pi 
Ration(1,3)+pi
(57)List 组合
class Link:
    empty=()
    def __init__(self,first,rest=empty):
        assert rest is Link.empty or isinstance(rest,Link)
        self.first=first
        self.rest=rest
    def __repr__(self):
        if self.rest:
            rest_repr=', '+repr(self.rest)
        else:
            rest_repr=''
        return 'Link('+repr(self.first)+rest_repr+')'
    def __str__(self):
        string='<'
        while self.rest is not Link.empty:
            string+=str(self.first)+', '
            self=self.rest
        return string+str(self.first)+'>'
def range_link(start,end):
    if start>=end:
        return Link.empty
   	return Link(start,range_link(start+1,end))

def map_link(f,s):
    if s is Link.empty:
        return s
    return Link(f(s.first))

def filter_link(f,s):
    if s is Link.empty:
        return s
    return Link(s.first,filter_link(f,s.rest)) if f(s.first) else filter_link(f,s.rest)

square,odd=lambda x:x*x,lambda x:x%2==1
list(map(square,filter(odd,range(1,6))))
map_link(square,filter_link(odd,range_link(1,6)))

s=Link(1,Link(2,Link(3)))
s.first=5
t=s.rest
t.rest=s
s.first
s.rest.rest.rest.first
(58)List 修改 add
def add(s,v):
    assert s is not Link.empty
    if v<s.first:
        s.rest=Link(s.first,s.rest)
        s.first=v
    elif v>s.first
    	s.rest=add(s.rest,v) if s.rest is not Link.empty else Link(v)
    return s
(59)tree 类
class Tree:
    def __init__(self,label,branches=[]):
        self.label=label
        for branch in branches:
            assert isinstance(branch,Tree)
        self.branches=list(branches)
    def __repr__(self):
        if self.branches:
            branch_str=', '+repr(self.branches)
        else:
            branch_str=''
        return 'Tree{{0},{1}}'.format(repr(self.label),branch_str)
    def __str__(self):
        return '\n'.join(self.indented())
    def indented(self):
        lines=[]
        for b in self.branches:
            for line in b.indented():
                lines.append('  '+line)
        return [str(self.line)]+lines
   	def is_leaf(self):
        return not self.branches
def fib_tree(n):
    if n==0 or n==1:
        return Tree(n)
    else:
        left=fib_tree(n-2)
        right=fib_tree(n-1)
        fib_n=left.label+right.label
        return Tree(fib,[left,right])
def tree(label,branches=[]):
    for branch in branches:
        assert is_tree(branch)
    return [label]+list(branches)
def label(tree):
    return tree[0]
def branches(tree):
    return tree[1:]
def fib_tree(n):
    if n==0 or n==1:
        return tree(n)
    else:
        left=fib_tree(n-2)
        right=fib_tree(n-1)
        fib_n=label(left)+label(right)
        return tree(fib_n,[left,right])
# 删减
def prune(t,n):
    assert n!=t.label
    t.branches=[b for b in t.branches if b.label!=n]
    for b in t.branches:
        prune(b,n)
# 叶节点
def leaves(tree):
    if tree.is_leaf():
        return [tree.label]
    return sum([leaves(b) for b in tree.branches],[])
# 高度
def height(tree):
    if tree.is_leaf():
        return 0
    return 1+max([height(b) for b in tree.branches])
(60)Fibonacci 和 记忆化
def fib(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fib(n-2)+fib(n-1)
def memo(f):
    cache={}
    def memoized(n):
        if n not in cache.keys():
            cache[n]=f(n)
        return cache[n]
    return memorized
fib_memo=memo(fib)
fib(5)
fib(6)
fib_memo(5)
fib_memo(6)
# 添加记忆化后的Fibonacci
def make_memo_fib():
    cache={0:0,1:1}
    def memo_fib(n):
        if n in cache:
            return cache[n]
       	res=mem_fib(n-2)+mem_fib(n-1)
        cache[n]=res
        return cache[n]
    return memo_fib
memo_fib=make_memo_fib()
memo_fib(20)
(61)复杂度
def exp(b,n):
    if n==0:
        return 1
    else:
        return b*exp(b,n-1)
def exp_fast(b,n):
    if n==0:
        return 1
    elif n%2==0:
        return square(exp_fast(b,n//2))
    else:
        return b*exp_fast(b,n-1)
def square(x):
    return x*x

(62)线性时间求列表重复元素(有序的列表)
# 暴力
def brute_overlap(s,t):
    count=0
    for i in s:
        for j in t:
            if i==j:
                count+=1
# 快速求解
def fast_overlap(s,t):
    count,i,j=0,0,0
	while i<len(s) and j<len(t):
        if s[i]<t[j]:
            i=i+1
        elif s[i]>t[j]:
            j=j+1
        else:
            count,i,j=count+1,i+1,j+1
    return count
(63)集合 sets
s={'one','two','three','four','four'}
print(s)
print('three' in s)
print(len(s))
print(s.union({'one','five'}))
s.intersection({'six','five','four','three'})
a=['first','second','third']
b=('first','second','third')
d={'first','second','third'}
e={1:'first',2:'second',3:'third'}
(64)控制流
def xk(c,d):
    if c==4:
        return 6
   	elif d>=4:
        return 6+7+c
    else:
        return 25
xk(10,10)
xk(4,6)
def how_big(x):
    if x>10:
        print('huge')
    elif x>5:
        print('big')
    elif x>0:
        print('small')
    else:
        print('nothing')
how_big(7)
how_big(12)
n=3
while n>=0:
    n-=1
    print(n)
positive=28
while positive:
    print('positive?')
    positive-=3
positive=-9
negative=-12
while negative:
    if positive:
        print(negative)
  	positive+=3
    negative+=3
(65)逻辑表达式
True and 13
False or 0
not 10
not None
True and 1/0 and False
True or 1/0 or False
True and 0
False or 1
1 and 3 and 6 and 10 and 15
-1 and 1>0
0 or False or 2 or 1/0
not 0
(1+1) and 1
1/0 or True
(True )
(66)error
print(__debug__)
def error():
    assert False

error()


def error():
    raise TypeError('a test type error')
    
def error():
    raise TypeError('a test type error')

try:
    error()
except TypeError as z:
    print(z)
def invert(x):
    inverse=1/x
    print('Never printed if x is 0')
    return inverse

def invert_safe(x):
    try:
        return invert(x)
    except ZeroDivisionError as e:
        return str(e)
(67)reduce

reduce(mul,[2,4,8],1)
# mul(mul(mul(1,2),4),8)
def reduce(f,s,initial):
    if not s:
        return initial
   	return reduce(f,s[1:], f(initial,s[0]))
def divide_all(n,ds):
    from operator import truediv
    try:
        return reduce(truediv,ds,n)
    except ZeroDivisionError:
        return float('inf')

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BoneInscri

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值