Home >Backend Development >Python Tutorial >Detailed explanation of examples of cracking guessing games using Python
This article mainly introduces the algorithm for cracking the guessing game in Python, briefly describes the principle of the guessing game, and analyzes the relevant implementation techniques of Python to crack the guessing game in the form of specific examples. Friends in need can refer to the following
The example of this article describes the implementation of Python to crack the guessing game algorithm. Share it with everyone for your reference, the details are as follows:
The chat robot in the QQ group will launch a guessing game. The gameplay is as follows:
1. The user sends #guessing the number to the group
2. Robot response: Guessing has started, the range is a number between 1-10000
3. You send #guess[123] to the group
4. Robot response: Is it too big or too small? Yes, or congratulations on your guess
5. You guess a smaller or larger number based on the 123 you just guessed, and return, send #guess number[111], that is, return to step 2
Then the best guessing method is definitely to find the number in the middle. Since mental arithmetic is time-consuming, I directly use the python script to crack this:
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'huhu, <huyoo353@126.com>' def find_middle(start, end): #print start, end return round((start+end)/2.0) if __name__ == '__main__': start, end = '','' text = raw_input(u"> 输入猜数的范围(如:421-499 或者421 499 或者421,499):").decode('gb18030') spliters = '-, ' for c in spliters: if text.find(c) != -1: num_list = text.split(c) if ''.join(num_list).isdigit(): start, end = num_list[0],num_list[1] break if start == '' or end == '': print u'范围不正确' else: start = int(start) end = int(end) count = 1 last_guess = find_middle(start,end) while 1: result = raw_input(u"放弃猜测直接回车, 等于输入=, 小了输入1, 大了请输入2\n>>> #猜数[%d] ,对吗?> " % last_guess ).decode('gb18030') #print type(text) if result in ['q','e','exit','quit','bye',u'退出']: print 'Bye!' break else: result=result.strip() if result == '1': start = last_guess last_guess = find_middle(last_guess,end) elif result == '2': end = last_guess last_guess = find_middle(start,last_guess) elif result == '=': print u'恭喜猜中, 共猜了%d次' % count print u'#猜数[%d]' % last_guess break else: # continue count += 1
The above is the detailed content of Detailed explanation of examples of cracking guessing games using Python. For more information, please follow other related articles on the PHP Chinese website!