#A plus Abs B
from operator import add , sub ,mul
def a_plus_abs_b(a,b):
if b < 0:
f = sub
else:
f = add
return f(a,b)
#将三个数中最小的两个数的平方相加,且函数只能写一行
def two_of_three(x,y,z):
return sub(add(add(mul(x,x),mul(y,y)),mul(z,z)),mul(max(x,y,z),max(x,y,z)))
#求大于1的整数的最大正因子
def largest_factor(n):
for i in range(n-1,0,-1):
if n%i == 0:
return i
return None
def if_function(condition,true_result,false_result):
if condition:
return true_result
else:
return false_result
def with_if_statement():
if cond():
return true_func()
else:
return false_func()
def with_if_function():
return if_function(cond(),true_func(),false_func())
def cond():
return False
def true_func():
print(42)
def false_func():
print(47)
这一道题需要注意函数参数在传递时是先求值的。
#Hailstonw
def hailstone(n):
i=1
while n!=1:
print(n)
if n%2 == 0:
n=n//2
else:
n=n*3+1
i=i+1
print(n)
return i