程序代码:
# 題目(1)
# 題目(1a):解答
def SUM(x, y): # 注:因為小寫sum是python內置函數,雖然沒有太大影響,但還命名還是建議用其它字母,這裡用大寫SUM
if x > y: return
result = x
nextNumber = x
while (nextNumber < y):
nextNumber += 1
result += nextNumber
return result
# 題目(1b):解答
def prove(x, y):
if x > y: return
return SUM(x, y) == sum(list(map(lambda n: n+1, range(x-1, y))))
# ---------------------------------------------------------------------
# 題目(2)
# 題目(2a):解答
# table
# 0 1
# 0 00 01
# 1 01 10
# non-negative integer 0 1 2
# binary digits 00 01 10
# 題目(2b):解答
def PROC0(a, b): # PROC0
c = bin(int(a, 2)+int(b, 2))
if len(c) < 4: # 長度小於 2+2 (2是因為包含前面的'0b',比如3的二進制數字是:'0b11')
c = c.replace('0b', ('0b'+('0'*(4-len(c)))))
return c[2:] # 只回傳binary digits,前面的'0b'不要
# non-negative integer 0 1 2 3 4 5 6 7
# THREE binary digits 000 001 010 011 100 101 110 111
def PROC1(x, y, z): # PROC1
c = bin(int(x, 2)+int(y, 2)+int(z, 2))
if len(c) < 5: # 長度小於 2+3 (2是因為包含前面的'0b',比如3的二進制數字是:'0b11')
c = c.replace('0b', ('0b'+('0'*(5-len(c)))))
return c[2:] # 只回傳binary digits,前面的'0b'不要
# ---------------------------------------------------------------------
# 題目(3):解答
# 自然底數/尤拉數 e(Euler's number)
def compute_e(k):
if k < 0: return
import math
return sum(list(map(lambda n: (1/(math.factorial(n))), range(k+1))))
# ---------------------------------------------------------------------
# 測試
if __name__ == '__main__':
x, y = 22, 314
print(SUM(x, y)) # 49224
print(prove(x, y)) # True
a, b = '0', '1'
print(PROC0(a, b)) # 01
x, y, z = '1', '0', '1'
print(PROC1(x, y, z)) # 010
k = 5
print(compute_e(k)) # 2.7166666666666663
小弟只是複習與學習,如果有誤,請指教,願意更改
[此贴子已经被作者于2021-8-3 14:09编辑过]