Python实现破解猜数游戏算法示例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现破解猜数游戏算法。分享给大家供大家参考,具体如下:

QQ群里的聊天机器人会发起猜数小游戏. 玩法如下:

1. 用户发 #猜数    到群里
2. 机器人响应: 猜数已经开始, 范围是1-10000之间的某个数
3. 你发送 #猜数[123] 到群里
4. 机器人响应: 大了或者小了, 或者恭喜你猜中了
5. 你根据刚才猜的123, 和返回, 猜一个更小或更大的数, 发送 #猜数[111] , 即返回第2步

那么最好的猜测方法肯定是找居中的数了, 由于心算耗时, 所以直接上python脚本破解这个:

#!/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

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python队列、进程间通信、线程案例

进程互斥锁 多进程同时抢购余票 # 并发运行,效率高,但竞争写同一文件,数据写入错乱 # data.json文件内容为 {"ticket_num": 1} import json...

Python通过递归遍历出集合中所有元素的方法

本文实例讲述了Python通过递归遍历出集合中所有元素的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:'''''通过递归遍历出集合中的所有元素 Created o...

浅谈python日志的配置文件路径问题

如下所示: import logging import logging.config logging.config.fileConfig(path) logger = logging...

python安装PIL模块时Unable to find vcvarsall.bat错误的解决方法

可能很多人遇到过这个错误,当使用setup.py安装python2.7图像处理模块PIL时,python默认会寻找电脑上以安装的vs2008.如果你没有安装vs2008,会出现Unabl...

python scipy卷积运算的实现方法

python scipy卷积运算的实现方法

scipy的signal模块经常用于信号处理,卷积、傅里叶变换、各种滤波、差值算法等。 *两个一维信号卷积 >>> import numpy as np >...