一個挺有趣的簡單小游戲.

一個挺有趣的簡單小游戲.

感覺最近這裡冷清了很多,所以給大家一個小游戲動動腦根.. =]

前幾天在一個 blog 上看到了一個有趣的簡單小游戲.
游戲說明:
1) 電腦隨機給出 1 到 9 不順序的 list  ---> [2,3,6,8,1,9,4,7,5] (for example)
玩法:
2 3 6 8 1 9 4 7 5
Reverse how many? 6
9 1 8 6 3 2 4 7 5
Reverse how many? 9
5 7 4 2 3 6 8 1 9
Reverse how many?
..........
2 1 3 4 5 6 7 8 9
Reverse how many? 2
Done! That took you 12 steps.

大家明白了嗎.....寫出這游戲吧...
過幾天我會 post 我的 code 上來.....
我的代码,欢迎指教。这个小游戏是有规律的哦,最多只要15步,玩的时候超过的话,就要好好想想了

#!/usr/bin/env python
# File: numgame.py
# Author: gosman
# Date: 2007-7-15

import random

step = 0
numarray = range(1,10)
list = range(1,10)
random.shuffle(list)
while not(list == numarray):
    for i in range(9):
        print list[i],
    step = step + 1
    index = raw_input('\nReverse how many? ')
    index = int(index)
    tmp = list[0:index]
    tmp.reverse()
    list = tmp + list[index:]
print 'Done ! That took you %d steps.' % step
呵呵....終於有人來了..xD...!!

Gosman 你的 code 當然是沒錯...
但有沒有想過,只用不多於 10 行的 code 來寫(ofcause # not count as a line)??
用python的函数式编程能力
也许能用不多于10 行的 code 來写
以下是我的 code , 多多指教, 不知道可以不可以再精簡一點!!

import random

# generate a list of numbers 1-9 in random order
# for instance: [3,5,7,1,2,9,6,8,4]
numbers = random.sample(range(1,10), 9)
steps = 0

# numerbs != [1,2,3,4,5,6,7,8,9]
while numbers != range(1,10):
    # join the all 9 numbers together with a space
    # for instance: 2 9 3 6 1 8 7 5 4
    # or use  ' '.join( str(n) for n in numbers )
    print ' '.join(map(str,numbers))
    index = int(raw_input('Reverse how many? '))
    # here is the main part of the game.
    # index-1 is the range of the numbers you select,
    # and -1 is to reverse the selected numbers.
    numbers[:index] = numbers[index-1::-1]
    steps += 1
   
print 'Done! That took you %d steps.' % steps


我觉得如果是为了写着玩缩短是可以的,不过一般写程序没必要写这么短
从效率上讲
while numbers != range(1,10):
这个效率应该比下面的差一点
temp=range(1,10)
while numbers==temp
个人意见~~~
果然用了map
函数式编程里很重要的函数
这条语句能不能解释一下呢
numbers[:index] = numbers[index-1::-1]
自己试了一把,是把这部分数组倒转了一把!主要以前没用过::的用法!
[::] 這個用法是在 cookbook 中找到的...
原文如下:

[Copy to clipboard] [ - ]
CODE:
Strings are immutable, so, to reverse one, we need to make a copy. The simplest approach for reversing is to take an extended slice with a "step" of -1, so that the slicing proceeds backwards:

revchars = astring[::-1]