Rcjp's Weblog

October 10, 2007

Number reversing game

Filed under: python — rcjp @ 3:10 pm

Here is the reverse game where the object is to flip the initial numbers in a random sequence of 1..9 repeatedly until they are in order.

import random

numbers = random.sample(range(1,10), 9)
steps = 0

while numbers != sorted(numbers):
    print " ".join(map(str, numbers))
    nflip = int(raw_input("Flip how many? "))
    numbers[:nflip] = reversed(numbers[:nflip])
    steps += 1

print "Finished in %d steps." % steps

""" sample run...

In [6]: run finished/game.py
2 3 4 5 9 7 6 1 8
Flip how many? 4
5 4 3 2 9 7 6 1 8
Flip how many? 6
7 9 2 3 4 5 6 1 8
Flip how many? 8
1 6 5 4 3 2 9 7 8
Flip how many? 5
3 4 5 6 1 2 9 7 8
Flip how many? 7
9 2 1 6 5 4 3 7 8
Flip how many? 9
8 7 3 4 5 6 1 2 9
Flip how many? 8
2 1 6 5 4 3 7 8 9
Flip how many? 3
6 1 2 5 4 3 7 8 9
Flip how many? 6
3 4 5 2 1 6 7 8 9
Flip how many? 3
5 4 3 2 1 6 7 8 9
Flip how many? 5
Finished in 11 steps.
"""

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: