这个我学过么?

学习python3的野路子——函数

2019-03-02  本文已影响0人  HerdingCat

函数[1][2]由函数名,参数,函数主体,返回值构成。

以下是两道编程题。

# PAT中的基础编程题目集函数题7-13
def isShadow(Open, High, Low, Close): # 判断阴影类型
    if Low < Open and Low < Close and High > Open and High > Close:
        return ' with Lower Shadow and Upper Shadow'
    elif Low < Open and Low < Close:
        return ' with Lower Shadow'
    elif High > Open and High > Close:
        return ' with Upper Shadow'
    else :
        return ''

Open, High, Low, Close = input().split(' ')
if float(Open) > float(Close):
    print('BW-Solid' + isShadow(float(Open), float(High), float(Low), float(Close)))
elif float(Open) < float(Close):
    print('R-Hollow' + isShadow(float(Open), float(High), float(Low), float(Close)))
else :
    print('R-Cross' + isShadow(float(Open), float(High), float(Low), float(Close)))

以上程序中,涉及逻辑运算[3]。python3中的逻辑运算并不向C语言中的一样借助于符号。python3中的通过and实现,通过or实现,通过not实现。

以下是通过循环不断缩小区间从而实现二分法求根。

# PAT中的基础编程题目集函数题7-18
def f(x, coeff): # 定义多项式函数
    return ((coeff[0] * x + coeff[1]) * x + coeff[2]) * x + coeff[3]

coeff = input().split()
range = input().split() # 此处的range为变量
coeff[0] = float(coeff[0]); coeff[1] = float(coeff[1]); coeff[2] = float(coeff[2]); coeff[3] = float(coeff[3])
a = float(range[0]); b = float(range[1])
if f(a, coeff) == 0: # 考虑结果为断点的情况
    b = a
elif f(b, coeff) == 0:
    a = b
mid = (a + b) / 2
while f(mid, coeff) != 0 and b - a > 0.001: # 判断循环结束条件
    if f(a, coeff) * f(mid, coeff) < 0:
        b = mid
    elif f(mid, coeff) * f(b, coeff) < 0:
        a = mid
    mid = (a + b) / 2
print('%.2f' %(mid))

参考


  1. http://www.tutorialspoint.com/python/python_functions.htm

  2. https://www.jianshu.com/p/433fabbf2ba7

  3. https://blog.csdn.net/lqzdreamer/article/details/77171255

上一篇下一篇

猜你喜欢

热点阅读