1.设计程序,判断一个字符串是否对称

P96 案例4.1.3

def reverse(s):
    t = "" 
    for i in range(len(s)-1, -1, -1):
        t = t + s[i]
    return t
def isSymmetry(s):
    t = reverse(s)
    if s == t:
        return 1
    else:
        return 0

s = input("Enter a string:")
if isSymmetry(s) == 1: 
    print("对称!")
else:
    print("不对称!")

 

2.输入一个有效时间,并显示该时间

P78 案例 3.5.3

def myTime():
    h = int(input("请输入一个时针数:"))
    if h < 0 or h > 23:
        raise Exception("无效的时!")
    m = int(input("请输入一个分针数:"))
    if m < 0 or m > 59:
        raise Exception("无效的分!")
    s = int(input("请输入一个秒针数:"))
    if s < 0 or s > 59:
        raise Exception("无效的秒!")
    print("%02d: %02d: %02d" % (h, m, s))

try:
    myTime()
except Exception as e:
    print(e)

 

3.输入两个正整数,求出他们的最大公约数与最小公倍数

P62 案例3.1.1

def maxDivider(a, b):
    c = a  
    if b < a:
        c = b
    for d in range(c, 0, -1):
        if a%d == 0 and b%d == 0:
            return d

def minMultiplier(a, b):
    c = a 
    if b > a:
        c = b 
    m = a*b
    for d in range(c, m+1, 1):
        if d%a == 0 and d%b == 0:
            return d

a = int(input("a = "))
b = int(input("b = "))

print("最大公约数", maxDivider(a, b))
print("最小公倍数", minMultiplier(a, b))

 

4.验证歌德巴赫猜想

P69 案例3.3.3

def IsPrime(m):
    for n in range(2, m):
        if m%n == 0:
            return 0
    return 1

for n in range(6, 101, 2):
    for p in range(3, n+1, 2):
        q = n - p
        if IsPrime(p) and IsPrime(q):
            print(n, "=", p, "+", q)
            break

 

5.对一个正整数分解质因数,例如输入90,打印出90=2*3*3*5

P45 案例2.7.5

n = int(input("Enter a integer:"))
first = True
print(n, end=" ")
i = 2
while i <= n:
    while n%i == 0:
        if first:
            print("=", i, end=" ")
            first = False
        else:
            print("*", i, end=" ")
        n = n//i
    i = i + 1