guess.py文件可以作为模块被其他脚本调用，提供如下接口：

check：根据猜测数和预期数2个参数返回1A1B格式结果。

calculate：根据猜测数、该猜测数的1A1B格式结果,返回所有可能是正确答案的数据集。

``````#!/usr/bin/python
# -*- coding:utf-8 -*-

import random

def random_num():
#生成4位无重复数字的随机数(首位不可为0)
com_num = random.sample('123456789', 4)
com_num = ''.join(com_num)
return com_num

def player_input():
#判断玩家输入合法性
while(True):
try:
global player_num
z = int(player_num)
if(len(player_num) != 4):
print('Please enter a 4 DIGIT number.')
continue

except ValueError:
if player_num == 'quit':
exit()
print('Your input is not a number.')

else:
if(len(set(player_num)) != 4):
print('Please enter a number with different digits.')
continue
elif player_num[0] == 0:
print('Please enter a number that first number is not 0.')
continue
else:
return

def check(number, question):
#根据猜测数和被猜数计算返回1A1B样式的结果"(1, 1)"
number = str(number)
question = str(question)
global a_count
global b_count
a_count = 0
b_count = 0

for i in range(4):
for j in range(4):
if(number[i] == question[j]):
if(i == j):
a_count += 1
else:
b_count += 1

return (a_count, b_count)

def allowed_number(number):
#判断数字合法性
return len(str(number)) == 4 and len(set(str(number))) == 4

all_numbers = [number for number in range(1234, 9877) if allowed_number(number)]
#所有可能结果

#根据猜测数和1A1B结果计算返回所有可能结果
number = str(number)
global num_series
num_series = []

for possible_num in all_numbers:
num_series.append(possible_num)

return num_series

def history_rec(number):
#记录本轮游戏出现过的数字
global history
return history.append(int(number))

def del_history(num_series, history):
#删除本轮游戏中出现过的数字
for number in history:
if number in num_series:
num_series.remove(number)

return num_series

def ai_best():
#反馈个数指标评判答案最优解
global best

def history_area(num_series):
#计算保存最可能的值域，取历史值域及新值域的交集
global area
intersection = [i for i in area if i in num_series]
intersection = list(set(area).intersection(set(num_series)))
return intersection

print'''
----------Guess The Number Game: Player VS AI----------

You can input"quit"to exit

Rules:
1.Question number is a random 4 digit number without same digits (first digit can't be 0).

2.Player and AI guess the number one by one until Player Win or AI Win.

3.After every guess, program will return an answer of 1A1B like:"(1, 1)".
A value is the number of digit and position are all correct.
B value is just the number of digit is correct (position is wrong).'''

player_num = 0
ai_num = 0
random_number = random_num()
player_turn = 1
a_count = 0
best = (0, 0)
history = []
area = all_numbers

while(a_count != 4):
question = random_number
num_series = []
#玩家的回合
if player_turn:
player_input()
history_rec(player_num)
ai_best()
#电脑的回合
else:
ai_num = random.choice(area)
history_rec(ai_num)
print "\nAI's choice is", ai_num
ai_best()

num_series = del_history(calculate(player_num, best), history)
area = history_area(num_series)
print num_series
print area
player_turn = not player_turn
#输出胜负结果
if player_turn:
print("\nYou Win!")
else:
print("\nAI Win!")
``````

``````Traceback (most recent call last):
File "C:\Python27\guess.py", line 144, in <module>
ai_num = random.choice(area)
File "C:\Python27\lib\random.py", line 275, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range
``````

2个回答

nonlocal不支持python 2.x
https://cndenis.iteye.com/blog/1754743

python 2.x 官方马上就不维护了 最好用3.x 版本

Arrange the Bulls

public class Solution { public String getHint(String secret, String guess) { int bulls=0; int cows=0; char[] sec = secret.toCharArray(); char[] gue = guess.toCharArray(); int[] s=new int[10]; int[] g=new int[10]; for(int i=0;i<sec.length;i++){ if(sec[i]==gue[i]){ bulls++; }else{ s[sec[i]-'0']++; g[gue[i]-'0']++; } } for(int j=0;j<g.length;j++){ cows+=Math.min(s[j],g[j]); } return bulls+"A"+cows+"B"; } } 我不明白为什么要在s[sec[i]-'0']++;g[gue[i]-'0']++处-‘0’;而如果改为+‘0’，就会报越界错误Line 13: java.lang.ArrayIndexOutOfBoundsException: 97。请大神解答
Romeo Meets Juliet
Description Farmer John has two feuding herds of cattle, the Moontagues and the Cowpulets. One of the bulls in the Moontague herd, Romeo, has fallen in love with Juliet, a Cowpulet. Romeo would like to meet with Juliet, but he doesn't want the other members of the Cowpulet herd to find out. Romeo and Juliet want to meet and graze in as large a region as possible along the pasture fence. However, this region should not contain too many Cowpulets, otherwise the chance of the two being caught is too great. Romeo has determined where along the fence each of the N (1 <= N <= 1000) members of the Cowpulet herd grazes. The long straight fence contains P (1 <= P <= 1000) equally-spaced posts numbered 1..P. Each Cowpulet grazes between some pair of adjacent posts. Help Romeo determine the length of the largest contiguous region along the fence containing no more than C (0 <= C <= 1000) members of the Cowpulet herd. Input * Line 1: Three separated integers: N, P, and C * Lines 2..N+1: Each line contains an integer X, in the range 1..P-1, specifying that a member of the Cowpulet herd grazes between fence posts X and X+1. Multiple Cowpulets can graze between any given pair of fence posts. Output * Line 1: A single integer specifying the size (the number of gaps between fence posts) of the largest contiguous region containing at most C Cowpulets. Sample Input 2 6 1 2 3 Sample Output 3
Dart-a-Mania
Description The game of darts has many variations. One such variation is the game of 301. In the game of 301 each player starts with a score of 301 (hence the name). Each player, in turn, throws three darts to score points which are subtracted from the player's current score. For instance, if a player has a current score of 272 and scores 55 points with the three darts, the new score would be 217. Each dart that is tossed may strike regions on the dartboard that are numbered between 1 and 20. (A value of zero indicates that the player either missed the dartboard altogether or elected to not throw the dart.) A dart that strikes one of these regions will either score the number printed on the dartboard, double the number printed, or triple the number printed. For example, a player may score 17, 34, or 51 points with a toss of one dart that hits one of the regions marked with a 17. A third way to score points with one dart is to hit the BULLS EYE which is worth 50 points. (There is no provision for doubling or tripling the bull's eye score.) The first player to reduce his score to exactly zero wins the game. If a player scores more points than his/her current score, the player is said to have "busted" and the new score is returned to the last current score. Problem Statement Given a player's current dart score, write a program to calculate all the possible combinations and permutations of scores on throwing three darts that would reduce the player's score to exactly zero (meaning the player won the game). The output of the program should contain the number of combinatons and permutations found. For example, if the player's current score is 2, then there would be two combinations and six permutations. The combinations would be: 1) obtain a score of 2 on any one dart and zero on the other two, and 2) obtain a score of one on two different darts and zero on the third dart. The order in which this is accomplished is not important. With permutations the order is significant; therefore the six permutations would be as follows: Dart 1: 2 0 0 1 1 0 Dart 2: 0 2 0 1 0 1 Dart 3: 0 0 2 0 1 1 (Note: The program doesn't print out the actual permutations & combinations, just the total number of each.) Input The input contains a list of integers (each <= 999), one per line, that represent several players' current scores. A value of zero or less will signify the end of the input file. Output For each positive integer in the input file, 2 or 3 line(s) will be written to the std output. If the score can be reduced to zero, your program should write the lines: NUMBER OF COMBINATIONS THAT SCORES x IS c. NUMBER OF PERMUTATIONS THAT SCORES x IS p. where x is the value of the player's score while c and p are the total number of combinations and permutations possible, respectively. If it is impossible to reduce the player's score to zero, write the line: THE SCORE OF x CANNOT BE MADE WITH THREE DARTS. After the line(s) above are printed, your program should write a line of 70 asterisks to separate output for different scores. The message "END OF OUTPUT" should appear at the end of the output file. Sample Input 162 175 2 68 211 114 -100 Sample Output NUMBER OF COMBINATIONS THAT SCORES 162 IS 7. NUMBER OF PERMUTATIONS THAT SCORES 162 IS 28. ********************************************************************** THE SCORE OF 175 CANNOT BE MADE WITH THREE DARTS. ********************************************************************** NUMBER OF COMBINATIONS THAT SCORES 2 IS 2. NUMBER OF PERMUTATIONS THAT SCORES 2 IS 6. ********************************************************************** NUMBER OF COMBINATIONS THAT SCORES 68 IS 187. NUMBER OF PERMUTATIONS THAT SCORES 68 IS 1056. ********************************************************************** THE SCORE OF 211 CANNOT BE MADE WITH THREE DARTS. ********************************************************************** NUMBER OF COMBINATIONS THAT SCORES 114 IS 82. NUMBER OF PERMUTATIONS THAT SCORES 114 IS 445. ********************************************************************** END OF OUTPUT
android，JSON数据解析，解析集合里的数据，求代码

Java学习的正确打开方式

linux系列之常用运维命令整理笔录

python学习方法总结(内附python全套学习资料)

python 简易微信实现（注册登录+数据库存储+聊天+GUI+文件传输）
socket+tkinter详解+简易微信实现 历经多天的努力，查阅了许多大佬的博客后终于实现了一个简易的微信O(∩_∩)O~~ 简易数据库的实现 使用pands+CSV实现数据库框架搭建 import socket import threading from pandas import * import pymysql import csv # 创建DataFrame对象 # 存储用户数据的表（...

Python十大装B语法
Python 是一种代表简单思想的语言，其语法相对简单，很容易上手。不过，如果就此小视 Python 语法的精妙和深邃，那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点，并附上详细的实例代码。如能在实战中融会贯通、灵活使用，必将使代码更为精炼、高效，同时也会极大提升代码B格，使之看上去更老练，读起来更优雅。

2019年11月中国大陆编程语言排行榜
2019年11月2日，我统计了某招聘网站，获得有效程序员招聘数据9万条。针对招聘信息，提取编程语言关键字，并统计如下： 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...

《奇巧淫技》系列-python！！每天早上八点自动发送天气预报邮件到QQ邮箱

Python实例大全（基于Python3.7.4）

SQL-小白最佳入门sql查询一

JavaScript 为什么能活到现在？

Nginx 原理和架构
Nginx 是一个免费的，开源的，高性能的 HTTP 服务器和反向代理，以及 IMAP / POP3 代理服务器。Nginx 以其高性能，稳定性，丰富的功能，简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求，主要负责调度工作进程：加载配置、启动工作进程及非停升级。worker 进程负责处...

Python 编程开发 实用经验和技巧
Python是一门很灵活的语言，也有很多实用的方法，有时候实现一个功能可以用多种方法实现，我这里总结了一些常用的方法和技巧，包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等，会持续更新......

“狗屁不通文章生成器”登顶GitHub热榜，分分钟写出万字形式主义大作

《程序人生》系列-这个程序员只用了20行代码就拿了冠军

11月8日，由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办，科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。 　　区块链技术被认为是继蒸汽机、电力、互联网之后，下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力，电力解决了人类基本的生活需求，互联网彻底改变了信息传递的方式，区块链作为构造信任的技术有重要的价值。 　　1...
Python 植物大战僵尸代码实现(2):植物卡片选择和种植

Python3.7黑帽编程——病毒篇（基础篇）

8年经验面试官详解 Java 面试秘诀

1.两种思维方式在求职面试中，经常会考察这种问题：北京有多少量特斯拉汽车？某胡同口的煎饼摊一年能卖出多少个煎饼？深圳有多少个产品经理？一辆公交车里能装下多少个乒乓球？一个正常成年人有多少根头发？这类估算问题，被称为费米问题，是以科学家费米命名的。为什么面试会问这种问题呢？这类问题能把两类人清楚地区分出来。一类是具有文科思维的人，擅长赞叹和模糊想象，它主要依靠的是人的第一反应和直觉，比如小孩...
17张图带你解析红黑树的原理！保证你能看懂！

so easy！ 10行代码写个"狗屁不通"文章生成器

MySQL数据库总结