bitwise not - not what I expected

Elaine Jackson elainejackson7355 at home.com
Sun Aug 17 19:35:43 EDT 2003


In case any fellow newbies have been following this thread, here is the finished
Nim script. It doesn't use bit-manipulation as much as I thought it would.
(Still, I got the basics straight. Thanks again to everyone who helped out!) For
a readable account of the optimal strategy for Nim, see Hardy & Wright's
"Introduction to the Theory of Numbers". Peace.

## NIM
from random import random
piles=[0,0,0]

########################################

def take(n,pileNum):
    if piles[pileNum]>=n:
        piles[pileNum]=piles[pileNum]-n
        print piles
    else:
        print "illegal move"

########################################

def newGame():
    for i in range(3):
        piles[i]=int(9*random())+1
    print piles

########################################

def indexOfMax():
    returnValue=0
    for i in range(1,3):
        if piles[i]>piles[returnValue]:
            returnValue=i
    return returnValue

########################################

def leftmostBitIndex(n):
    if 0<n<pow(2,29):
        for i in range(1,31):
            if pow(2,i)>n:
                return (i-1)
    else:
        raise

########################################

def yourMove():
    magicNum=piles[0]^piles[1]^piles[2]
    if magicNum==0:
        i=indexOfMax()
        piles[i]=piles[i]-1
    else:
        magicIndex=leftmostBitIndex(magicNum)
        targetIndex=(-1)
        for i in range(3):
            if (piles[i]>>magicIndex)%2==1:
                targetNum=piles[i]
                targetIndex=i
                break
        replacement=0
        for i in range(magicIndex):
            magicDigit=(magicNum>>i)%2
            targetDigit=(piles[targetIndex]>>i)%2
            if magicDigit==1:
                replacementDigit=(magicDigit-targetDigit)
            else:
                replacementDigit=targetDigit
            replacement=replacement+replacementDigit*pow(2,i)
        newNum=targetNum-(targetNum%pow(2,magicIndex+1))+replacement
        piles[targetIndex]=newNum
        print piles

############ not used in this script:

def matilda(n):
    if 0<=n<pow(2,29):
        for i in range(1,31):
            iOnes=pow(2,i)-1
            if n<=iOnes:
                return iOnes-n
    else:
         raise






More information about the Python-list mailing list