24点游戏

写博客啊,写博客

 

\t ----------------三个空格

%i---------------%i和%d几乎一样,表示有符号的十进制

try ..except-----异常处理

ast模块,ast.parse

re模块,re.search

continue

from __future__ import division, print_function

 

 1 #coding:utf-8
 2 '''
 3  The 24 Game
 4  
 5  Given any four digits in the range 1 to 9, which may have repetitions,
 6  Using just the +, -, *, and / operators; and the possible use of
 7  brackets, (), show how to make an answer of 24.
 8  
 9  An answer of "q" will quit the game.
10  An answer of "!" will generate a new set of four digits.
11  Otherwise you are repeatedly asked for an expression until it evaluates to 24
12  
13  Note: you cannot form multiple digit numbers from the supplied digits,
14  so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
15  
16 '''
17 
18 from __future__ import division, print_function
19 import random, ast, re
20 import sys
21  
22 if sys.version_info[0]<3:input=raw_input #python版本号小于3,用raw_input代替input
23 
24 #随机生成4个数
25 def choose4():
26     'four random digits > 0 as characters'
27     return [str(random.randint(1,9)) for i in range(4)] #4个数组成列表,数字是字符串格式。例如['1','3','5','7']
28 
29 #显示生成的4个数
30 def welcome(digits):
31     print (__doc__)
32     print ("Your four digits:"+' '.join(digits)) #将列表转换成字符串,空一格
33 
34 #检查输入的表达式是否在给定的4个数里进行加减乘除括号运算
35 def check(answer,digits):
36     allowed = set('()+-*/\t'+''.join(digits)) # 用set集合去掉重复
37     ok = all(ch in allowed for ch in answer) and \
38     all (digits.count(dig) == answer.count(dig) for dig in set(digits))\
39     and not re.search('\d\d',answer)  #不允许两个数字连在一起,待理解re.search all是什么?----(digits.count(dig) == answer.count(dig) for dig in set(digits))相同的数字要一样多
40     if ok:
41         try: #try,except?异常处理ast.parse?语法分析
42             ast.parse(answer)
43         except:
44             ok = False
45     return ok
46 
47 #主程序
48 def main():
49     digits = choose4()
50     welcome(digits)
51     trial = 0
52     answer = ''
53     chk = ans = False
54     while  not (chk and ans == 24):
55         trial += 1
56         answer = raw_input("Expression %i: " % trial) 
57         chk = check(answer,digits)
58         if answer.lower() == 'q': #退出
59             break
60         if answer == '!': #换另外四个数
61             digits = choose4()
62             print ("New digits:",' '.join(digits))
63             continue #continue
64         if not chk:
65             print ("The input '%s' was wonky!" %answer) #不符合给定的4个数或者四则运算,%s代表?
66         else:
67             ans = eval(answer) #eval
68             print ("=",ans)
69             if ans == 24:
70                 print ("Thats right!")
71 
72     print ("Thank you and goodbye")
73 
74 main()

 

posted @ 2014-12-20 09:09  batur  阅读(172)  评论(0)    收藏  举报