python 示例(摘抄)

# 计算一元二次方程的根
import math

while True:
    a = float(input('Enter coefficient a: '))
    b = float(input('Enter coefficient b: '))
    c = float(input('Enter coefficient c: '))
    if a != 0:
        delta = b ** 2 - 4 * a * c
        if delta < 0:
            print('No solution')
        elif delta == 0:
            s = -b/(2 * a)
            print('s:', s)
        else:
            root = math.sqrt(delta)
            s1 = (-b + root) / (2 * a)
            s2 = (-b - root) / (2 * a)
            print('Two distinct solutions are:', s1, s2)
    ch = input('Quit?')
    if ch == 'q':
        break
# 汉诺塔问题
count = 0

def hanoi(n, A, B, C):
    global count
    if n == 1:
        print('Move', n, 'from', A, 'to', C)
        count += 1
    else:
        hanoi(n-1, A, C, B)
        print('Move', n, 'from', A, 'to', C)
        count += 1
        hanoi(n-1, B, A, C)
        
hanoi(2, 'Left', 'Mid', 'Right')
print(count)

-- 原文地址:MOOC 哈工大课程 《高级语言程序设计(Python)》 车万翔

posted on 2020-03-25 17:25  wangzhiliang  阅读(211)  评论(0编辑  收藏  举报

导航