Python趣味编程(一)破解刘谦的“读心术”(原创)

上周看到刘谦在表演“读心术”。

表演方式如下:

1. 让嘉宾心里默想一个数字,在0-63之间。

2. 依次给嘉宾看六张牌,每张牌上有若干个数字(我猜想是32个)。

3. 让嘉宾回答,心理默想的数字有没有在扑克牌上。

4. 六张牌看完,刘谦写出一个数字,然后让嘉宾说出心里默想的数。

5. 吻合,掌声雷动。

我看了之后,挺晕的……看来术业有专攻……这么简单的二进制问题,也能拿来做魔术表演。

于是写了个程序来模拟刘谦的魔术,变给老婆看……

1 import sys
2
3 NUM = 6
4 LINE_NUM = 70
5
6 maxMargin = 1 << NUM
7 numList = range(0, maxMargin)
8
9 resultNum = 0
10
11  for x in range(0, NUM):
12 print "=" * LINE_NUM
13 tmpSet = set([(tmpNum | 1 << x) for tmpNum in numList])
14 for (tmpNum, tmpCount) in zip(list(tmpSet), range(1, len(tmpSet) + 1)):
15 sys.stdout.write("%d\t" % tmpNum)
16 if tmpCount % 8 == 0:
17 print ""
18 print "=" * LINE_NUM
19 print ""
20
21 tmpStr = raw_input("Is the number in list? n(y/n)?\n")
22 tmpStr = tmpStr.strip()
23 if (tmpStr == "y"):
24 resultNum += 1 << x
25
26  print "The number is: %d" % resultNum

运行结果如下:(老婆心里默想的是17)

$ python guessNumberMagic.py
======================================================================
1 3 5 7 9 11 13 15
17 19 21 23 25 27 29 31
33 35 37 39 41 43 45 47
49 51 53 55 57 59 61 63
======================================================================

Is the number in list? n
(y/n)?
y
======================================================================
2 3 6 7 10 11 14 15
18 19 22 23 26 27 30 31
34 35 38 39 42 43 46 47
50 51 54 55 58 59 62 63
======================================================================

Is the number in list? n
(y/n)?
n
======================================================================
4 5 6 7 12 13 14 15
20 21 22 23 28 29 30 31
36 37 38 39 44 45 46 47
52 53 54 55 60 61 62 63
======================================================================

Is the number in list? n
(y/n)?
n
======================================================================
8 9 10 11 12 13 14 15
24 25 26 27 28 29 30 31
40 41 42 43 44 45 46 47
56 57 58 59 60 61 62 63
======================================================================

Is the number in list? n
(y/n)?
n
======================================================================
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
======================================================================

Is the number in list? n
(y/n)?
y
======================================================================
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
======================================================================

Is the number in list? n
(y/n)?
n
The number is:
17

果然猜出来了,老婆说没有脑筋急转弯好玩……

心里拔凉拔凉的……

posted @ 2011-07-12 10:51  毛豆子  阅读(2629)  评论(6编辑  收藏  举报