Python程式:解決豬雞同籠問題
阿新 • • 發佈:2018-12-16
''' 該問題類似於雞兔同籠問題,輸入腿和頭的個數,計算豬和雞的個數,採用窮舉法解決該問題。該問題來源於MIT計算機導論課程。 ''' def calculate(n_heads,n_legs): for n_chicks in range(0,n_heads+1): n_pigs=n_heads-n_chicks total_legs=4*n_pigs+2*n_chicks if total_legs==n_legs: return[n_pigs,n_chicks] return [None,None] def solve(): legs=int(input("輸入腿的個數:")) heads=int(input("輸入頭的個數:")) [pigs,chicks]=calculate(heads,legs) if pigs==None: print("輸入值無解") else: print("豬的個數為:",pigs) print("雞的個數為:",chicks) solve()