Python语言程序设计——实验五

2022/2/4 22:13:05

本文主要是介绍Python语言程序设计——实验五,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、编程求组合程序调用函数comb();comb()在执行过程中又调用了函数fac()。fac()的调用被嵌套在函数comb()的调用中。

n = eval(input("Input n: "))
m = eval(input("Input m: "))
def fac(k) :
    i = f = 1
    while i<=k :
        f = f*i
        i = i+1
    return f
def comb(n, m) :
    c = fac(m)//(fac(n)*fac(m-n))
    return c
print(comb(n, m))

2、请改正下面程序中存在的错误?

                def Sum(a,b,c):

                        print(a+b+c)

                t=(1,2,3)

                Sum(**t)      改为:Sum(*t)

3、请定义一个函数q(a, b, c),接收3个参数,可以使用全局变量__name__,进行测试,返回一元二次方程:ax2 + bx + c = 0的两个解。提示:计算平方根可以调用math.sqrt()函数。

 

import math
def q(a, b, c):
    if a == 0:
        print('函数无解。')
    else:
        dert = b * b - 4 * a * c
        x1 = (- b + math.sqrt ( dert )) / ( 2 * a )
        x2 = (- b - math.sqrt ( dert )) / ( 2 * a )
        return x1,x2
if __name__ == '__main__':
    print ( 'q(2, 3, 1) =' , q ( 2 , 3 , 1 ) )
    print ( 'q(1, 3, -4) =' , q ( 1 , 3 , -4 ) )

    if q ( 2 , 3 , 1 ) != (-0.5 , -1.0):
        print ( '测试失败' )
    elif q ( 1 , 3 , -4 ) != (1.0 , -4.0):
        print ( '测试失败' )
    else:
        print ( '测试成功' )

4、编写程序解决汉诺塔问题:有三根杆(编号A、B、C),在A杆自下而上、由大到小按顺序放置n个盘子(编号从n至1,即最下面盘子编号为n,最上面盘子编号为1)。目标:把A杆上的盘子全部移到C杆上,并仍保持原有顺序叠好。操作规则:每次只能移动一个盘子,并且在移动过程中三根杆上都始终保持大盘在下,小盘在上,操作过程中盘子可以置于A、B、C任一杆上。提示:编写递归函数解决该问题。

        我们可以理解move(n,a,b,c)函数中对应的a表示起始位置,b表示中间位置,c表示最终要移到的位置,可以分为下面3个部分理解:

                                1.将n-1个盘子从a移到b

                                2.将最后1个盘子从a移到c

                                3.将n-1个盘子从b移到c

def move (n,a,b,c):
    if n ==1:
        print('move',a,'-->',c)
    else:
        move(n-1,a,c,b) #把上面n-1个从a-->b
        move(1,a,b,c) #把最下面一个从a-->c
        move(n-1,b,a,c) #把上面n-1个从b-->c
n=float(input('请输入n='))
print('结果如下所示:')
print(move(n,'A','B','C'))

                第二种:

step=0
def move(n,a,b,c):
    global step
    if n==1:  #这个地方就是递归函数调用终止的条件
        print(a,'-->',c)
        step=step+1
    else:
        move(n-1,a,c,b)  #把上面n-1个从a-->b
        move(1,a,b,c)    #把最下面一个从a-->c
        move(n-1,b,a,c)  #把上面n-1个从b-->c

def main():
    n=eval(input("please input the numbers of the plates:"))
    move(n,'A','B','C')  #这里的A B C 表示圆柱
    print("the total steps to move the plates from a to c is {}".format(step))
main()



这篇关于Python语言程序设计——实验五的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程