APlusAbsBfromoperatorimportadd,subdefa_plus_abs_b(a,b):"""返回a+abs(b),但不调用abs。>>>a_plus_abs_b(2,3)5>>>a_plus_abs_b(2,-3)5>>>#检查你没有改变返回语句!>>>importinspect,re>>>re.findall(r'^\s*(return.*)',inspect.getsource(a_plus_abs_b),re.M)['returnf(a,b)']"""ifb<0:f=subelse:f=addreturnf(a,b)TwoofThreedeftwo_of_three(x,y,z):"""返回a*a+b*b,其中a,b为正数x,y,z中最小的两个成员。>>>two_of_three(1,2,3)5>>>two_of_three(5,3,1)10>>>two_of_three(10,2,8)68>>>two_of_three(5,5,5)50>>>#检查你的代码只包含一个表达式(这个文档字符串)>>>#返回语句>>>importinspect,ast>>>[type(x).__name__forxinast.parse(inspect.getsource(two_of_three)).body[0].body]['Expr','Return']"""返回x**2+y**2+z**2-max(x,y,z)**2LargestFactordeflargest_factor(n):"""返回n中小于n的最大因子。>>>largest_factor(15)#因子是1,3,55>>>largest_factor(80)#因子是1,2,4,5,8,10,16,20,4040>>>largest_factor(13)#factoris1since13isprime1""""***YourCODEHERE***"factor=n-1whilen>0:ifn%factor==0:returnfactorfactor-=1IfFunctionvsStatement关键是如果我不满足条件,函数还会执行吗?可以看出with_if_dunction中使用了call表达式,即使cond返回False,第二个函数true_func()还是会执行defcond():"***YourCODEHERE***"returnFalsedeftrue_func():"***YOURCODEHERE***"print(42)deffalse_func():"***YourCODEHERE***"打印(47)海尔斯托nedefhailstone(n):"""打印从n开始的冰雹序列并返回它的长度。>>>a=hailstone(10)105168421>>>a7""""***YOUR此处代码***"count=0whilen!=1:count+=1print(n)ifn%2==1:n=n*3+1else:n//=2返回计数
