最近开始学习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 = 0 10 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 = True 18 elif user_inp == 'h': 19 hi = guess 20 elif user_inp == 'l': 21 lo = guess 22 else: 23 print("Sorry, I did not understand your input.") 24 print('Game over. Your secret number was: ' + str(guess))