最近開始學習mit的python課程,其中手工實現的一個關于二分法查找的練習代碼個人感覺比較有參考價值,貼上來分享交流一下。
主要功能是在1-100中自己猜測一個數值,隨后系統產生數值看是否符合猜測,如果不符合選擇高于或者低于猜測數值,系統繼續產生隨機數,最后成功找到猜測值。
實現方法為采用二分法,每次取中值,如果高了則繼續取下半部分的中值,如果低了則取上半部分的中值,以此類推,最后找到正確猜測值。
1 from pip.backwardcompat import raw_input 2 3 PRint("Please think of a number between 0 and 100!") 4 5 #設初始值 6 hi = 100 7 lo = 0 8 guessed = False 9 guess = 010 while not guessed:11 guess = (int)((hi + lo)/2) #注意此處將結果強轉為int型,否則系統值將會是浮點數12 print("Is your secret number " + str(guess) + "?")13 #輸入語句14 user_inp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")15 #c為猜測正確,h為數值高了,l為低了16 if user_inp == 'c':17 guessed = True18 elif user_inp == 'h':19 hi = guess20 elif user_inp == 'l':21 lo = guess22 else:23 print("Sorry, I did not understand your input.")24 print('Game over. Your secret number was: ' + str(guess))
新聞熱點
疑難解答