1. 程式人生 > >Python解決階乘計算問題

Python解決階乘計算問題

最近面試遇到的幾個問題,記錄。

1. 問題如下


程式碼如下。

對於該題的測試用例設計需要考慮全面。

def FirstFactorial(num):
    if num >18:
        print("You should input a number between 1 and 18")
        num2 = int(raw_input("input an integer number in range 1-18:"))
        cal(num2)
        print("%d factorials is %d" % (num2, firstNum))
    elif num == 0:
        cal(num)
    elif num < 0:
        print("Minus No Factorials")
    else:
        cal(num)
        print("%d factorials is %d" % (num, firstNum))
def cal(recNum):
    global firstNum
    for i in range(1, recNum + 1):
        firstNum = firstNum * i
    return firstNum

if __name__=='__main__':
    # input always be an integer
    for j in range(2):
        try:
            orginalNum = int(raw_input("input an integer number in range 1-18:"))
        except Exception as e:
            print("It's not Integer", e)
        else:
            firstNum = 1
            FirstFactorial(orginalNum)